Basic Usage StackExchange.Redis 的文档解释说 ConnectionMultiplexer
是长期存在的,预计会被重用。
但是当与服务器的连接断开时怎么办? ConnectionMultiplexer
是否自动重新连接,或者是否需要像 this answer 中那样编写代码(引用那个答案):
if (RedisConnection == null || !RedisConnection.IsConnected)
{
RedisConnection = ConnectionMultiplexer.Connect(...);
}
RedisCacheDb = RedisConnection.GetDatabase();
上面的代码是否适合处理断开连接的恢复,或者它实际上会导致多个 ConnectionMultiplexer
实例?同样,应该如何解释 IsConnected
属性?
[旁白:我认为上面的代码是一种非常糟糕的惰性初始化形式,尤其是在多线程环境中 - 参见 Jon Skeet's article on Singletons ].
最佳答案
这是 pattern recommended by the Azure Redis Cache team :
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});
public static ConnectionMultiplexer Connection {
get {
return lazyConnection.Value;
}
}
几个要点:
- 它使用 Lazy
来处理线程安全的初始化 - 它设置“abortConnect=false”,这意味着如果初始连接尝试失败,ConnectionMultiplexer 将在后台静默重试而不是抛出异常。
- 它不会检查 IsConnected 属性,因为如果连接断开,ConnectionMultiplexer 会在后台自动重试。
关于c# - ConnectionMultiplexer 如何处理断开连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792196/