ConnectionMultiplexer 如何处理断开连接? [英] How does ConnectionMultiplexer deal with disconnects?
问题描述
StackExchange.Redis 的基本用法文档解释说 ConnectionMultiplexer
是长期存在的,预计会被重用.
The Basic Usage documentation for StackExchange.Redis explains that the ConnectionMultiplexer
is long-lived and is expected to be reused.
但是当与服务器的连接中断时怎么办?ConnectionMultiplexer
是否会自动重新连接,或者是否有必要像 这个答案 中那样编写代码(引用那个答案):
But what about when the connection to the server is broken? Does ConnectionMultiplexer
automatically reconnect, or is it necessary to write code as in this answer (quoting that answer):
if (RedisConnection == null || !RedisConnection.IsConnected)
{
RedisConnection = ConnectionMultiplexer.Connect(...);
}
RedisCacheDb = RedisConnection.GetDatabase();
上面的代码是否可以很好地处理断开连接的恢复,还是实际上会导致多个 ConnectionMultiplexer
实例?同样,应该如何解释 IsConnected
属性?
Is the above code something good to handle recovery from disconnects, or would it actually result in multiple ConnectionMultiplexer
instances? Along the same lines, how should the IsConnected
property be interpreted?
[旁白:我相信上面的代码是一种非常糟糕的延迟初始化形式,尤其是在多线程环境中 - 请参阅 Jon Skeet 关于单身人士的文章].
推荐答案
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<T>处理线程安全的初始化
- 它设置了abortConnect=false",这意味着如果初始连接尝试失败,ConnectionMultiplexer 将在后台静默重试而不是抛出异常.
- 它不检查 IsConnected 属性,因为如果连接断开,ConnectionMultiplexer 将在后台自动重试.
- It uses Lazy<T> to handle thread-safe initialization
- It sets "abortConnect=false", which means if the initial connect attempt fails, the ConnectionMultiplexer will silently retry in the background rather than throw an exception.
- It does not check the IsConnected property, since ConnectionMultiplexer will automatically retry in the background if the connection is dropped.
这篇关于ConnectionMultiplexer 如何处理断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!