c# - ConnectionMultiplexer 如何处理断开连接?

标签 c# redis stackexchange.redis

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/

相关文章:

c# - Redis 用 'QUEUED' 回复所有查询

c# - Windows 匿名管道上的非阻塞 io

c# - 我可以选择在运行时关闭 JsonIgnore 属性吗?

redis - 尝试将 : Changing . NET 标准库的依赖项解析为 NET Core - Microsoft.Extensions.Primitives

node.js 使用 Redis 使用 ttl 创建作业

azure - Redis 的理想值大小范围是多少? 100KB 太大了吗?

redis - 什么是 Booksleave IKeyCommands.Find 等价于 StackExchange.Redis

c# - 为什么带有 protobuf 的 redis 将空数组保存为 null?

c# - Array.Length 和 Array.Count() 之间的区别

c# - 托管元数据字段中的 AfterProperties 和 BeforeProperties 根据语言返回不同的字符串