/// <summary> /// 操作从库,一般是不分主从的set,不能乱了 /// </summary> /// <param name="fn">fn</param> /// <returns>bool</returns> private bool setSlave(Func <IDatabase, bool> fn) { int error = 0; gotHere: if (this.SlaveServers == null || this.SlaveServers.Length < 1) { return(false); } int num = 0; ConnectionMultiplexer conn = null; for (int i = 0; i < this.SlaveServers.Length; i++) { try { conn = RedisConnectionManager.GetConnection(this.SlaveServers[i]); if (conn == null) { continue; } IDatabase db = conn.GetDatabase(this.SlaveServers[i].DbIndex); num += fn(db) ? 1 : 0; } catch (Exception ex) { if (error < 2) { if (conn != null) { RedisConnectionManager.Dispose(this.SlaveServers[i], conn); // conn = null; } error += 1; System.Threading.Thread.Sleep(1000); goto gotHere; } logger.LogError(ex, "RedisNode.SetSlave.Error"); } } return(num == this.SlaveServers.Length); }
private T GetSlave <T>(Func <IDatabase, T> fn) { int error = 0; gotoHere: ConnectionMultiplexer conn = null; int idx = DateTime.Now.Millisecond % SlaveServers.Length; // 如果读从库,随机取 try { conn = RedisConnectionManager.GetConnection(SlaveServers[idx]); if (conn == null) { return(default(T)); } IDatabase db = conn.GetDatabase(this.SlaveServers[idx].DbIndex); try { return(fn(db)); // 回调异常和连接异常分开处理,回调异常是业务处理异常,连接异常底层做重试 } catch (Exception e) { logger.LogError(e, $"RedisNode.GetSlave<T>类型{typeof(T).FullName}转换异常"); return(default(T)); } } catch (Exception ex) { if (error < 2) { if (conn != null) { // 释放掉坏连接 RedisConnectionManager.Dispose(SlaveServers[idx], conn); } error += 1; System.Threading.Thread.Sleep(1000); goto gotoHere; } logger.LogError(ex, "RedisNode.GetSlave<T>.Error"); return(default(T)); } }
/// <summary> /// 操作主库,一般都是set操作 /// </summary> /// <param name="fn">fn</param> /// <returns>bool</returns> private bool setMaster(Func <IDatabase, bool> fn) { int error = 0; gotoHere: ConnectionMultiplexer conn = null; try { conn = RedisConnectionManager.GetConnection(this.MasterServer); if (conn == null) { return(false); } IDatabase db = conn.GetDatabase(this.MasterServer.DbIndex); return(fn(db)); } catch (Exception ex) { if (error < 2)//出错可以重试两次 { if (conn != null) { RedisConnectionManager.Dispose(this.MasterServer, conn); // conn = null;//把这个链接设置为空,防止第二次还是被取出来 } error += 1; System.Threading.Thread.Sleep(1000); goto gotoHere; } logger.LogError(ex, "RedisNode.setMaster.Error"); return(false); } }