如何ConnectionMultiplexer处理断开? [英] How does ConnectionMultiplexer deal with disconnects?

查看:4813
本文介绍了如何ConnectionMultiplexer处理断开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关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?

旁白:我相信上面的代码是延迟初始化的一个非常糟糕的形式,尤其是在多线程环境 - 看乔恩斯基特对单身]文章。

[Aside: I believe the above code is a pretty bad form of lazy initialization, particularly in multithreaded environments - see Jon Skeet's article on Singletons].

推荐答案

下面是的模式蔚蓝Redis的缓存小组推荐:

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;
    }
}



几个要点:

A few important points:


  • 它采用懒< T>处理线程安全的初始化

  • 它集abortConnect =假,这意味着如果初始连接尝试失败,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆