/// <summary> /// 建立连接 /// </summary> /// <returns></returns> RedisConnection Connect(RedisConnection old = null) { try { if (old == null) { old = new RedisConnection() { Connection = ConnectionMultiplexer.Connect(_connectStr), Repairing = false }; } else { old.Connection = ConnectionMultiplexer.Connect(_connectStr); old.Repairing = false; } SERedisConnectionDefenderEx.Repaired[_sectionName] = new SectionInfo { SectionName = _sectionName, Created = DateTime.Now }; SERedisConnectionCache.Set(_sectionName, old); return(old); } catch (Exception ex) { throw new Exception("SERedisConnectionDefender.Connect 异常,connectStr:" + _connectStr, ex); } }
/// <summary> /// redis 连接 /// </summary> /// <param name="sectionName"></param> /// <param name="dbIndex"></param> public SERedisConnection(string sectionName, int dbIndex) { _sectionName = sectionName; _dbIndex = dbIndex; RedisConnection = SERedisConnectionCache.Get(_sectionName); if (RedisConnection == null || RedisConnection.Connection == null || !RedisConnection.Connection.IsConnected || RedisConnection.Repairing) { throw new Exception("Redis 连接未初始化或正在修复中,无法执行此操作,sectionName:" + sectionName); } Configuration = RedisConnection.Connection.Configuration; }
/// <summary> /// 释放连接 /// </summary> /// <param name="old"></param> void DisConnect(RedisConnection old = null) { if (old == null) { return; } SERedisConnectionCache.Remove(_sectionName); old.Connection.Close(); old.Connection.Dispose(); old.Connection = null; }
/// <summary> /// 初始化池,类似于构造方法 /// 不要重复调用 /// </summary> /// <param name="redisConfig"></param> public void Init(RedisConfig redisConfig) { if (redisConfig == null) { throw new Exception("传入的redisConfig实例不能空"); } _sectionName = redisConfig.SectionName; _BusyRetry = redisConfig.BusyRetry; _BusyRetryWaitMS = redisConfig.BusyRetryWaitMS; if (string.IsNullOrWhiteSpace(_sectionName)) { throw new Exception("redisConfig.SectionName不能为空"); } lock (locker) { if (SERedisConnectionCache.Exists(_sectionName)) { return; } var configStr = GenerateConnectionString(redisConfig); if ((redisConfig.PoolSize < 1) || (redisConfig.PoolSize > 100)) { redisConfig.PoolSize = 1; } //哨兵特殊处理 if (redisConfig.Type == RedisConnectType.Sentinel) { var sentinel = new SESentinelClient(_sectionName, configStr, redisConfig.PoolSize, redisConfig.Password); sentinel.OnRedisServerChanged += sentinel_OnRedisServerChanged; var operateRedisConnecitonString = sentinel.Start(); _SentinelPool.AddOrUpdate(_sectionName + "_" + redisConfig.ServiceName, sentinel, (x, y) => sentinel); SERedisConnectionCache.Init(_sectionName, operateRedisConnecitonString); } else { SERedisConnectionCache.Init(_sectionName, configStr); } } }
/// <summary> /// 哨兵监测事件 /// </summary> /// <param name="section"></param> /// <param name="newConnectionString"></param> private void sentinel_OnRedisServerChanged(string section, string newConnectionString) { SERedisConnectionCache.Init(_sectionName, newConnectionString); }