更新 ConnectionMultiplexer 的连接字符串是否可行,还是应该重新创建一个新的连接?

6
我们正在使用StackExchange.Redis客户端。我们还在使用Sentinel,它告诉我们Redis主服务器何时更改。既然我们已经创建了我们的连接(作为推荐的Lazy<IConnectionMultiplexer>),我们想知道将连接信息更改为指向新的Redis主服务器的最佳方法是什么?
我们看到几个选项:
  1. 当来自Sentinel的通知到达时,创建一个新的Lazy<IConnectionMultiplexer>
  2. 更改现有连接多路复用器上的连接信息
#2是否可行?
我们目前的方式:
    private Lazy<IConnectionMultiplexer> CreateRedisConnection()
    {
        return new Lazy<IConnectionMultiplexer>(
            () =>
            {
                ConnectionMultiplexer multiplexer = null;

                    //Connect to Sentinel so we can find the redis master
                    ConnectionMultiplexer sentinelMultiplexer = ConnectionMultiplexer.Connect(SentinelOptions);

                    string masterNodeAddress = GetMasterNodeAddress(sentinelMultiplexer);

                    return ConnectionMultiplexer.Connect(masterNode);
            }
        );
    }

接收通知后,我们只需重新调用CreateRedisConnection()函数。

但这将完全重新创建连接多路复用器,而非采用更轻量级的方法(这可能不可行)。

1个回答

0
处理StackExchange.Redis与Sentinel中的主节点更改的推荐方法是在检测到更改时创建一个新的ConnectionMultiplexer。与尝试修改现有的ConnectionMultiplexer相比,重新创建ConnectionMultiplexer是一种更安全和更直接的方法。
如果主节点发生更改,创建一个新的ConnectionMultiplexer允许库与新的主节点建立连接并透明地处理更改。
以下是对您的代码进行简单修改以说明这种方法的示例:
private Lazy<IConnectionMultiplexer> redisConnection;

private void InitializeRedisConnection()
{
    redisConnection = new Lazy<IConnectionMultiplexer>(() =>
    {
        // Connect to Sentinel to find the Redis master
        ConnectionMultiplexer sentinelMultiplexer = ConnectionMultiplexer.Connect(SentinelOptions);
        string masterNodeAddress = GetMasterNodeAddress(sentinelMultiplexer);

        // Connect to the Redis master
        return ConnectionMultiplexer.Connect(masterNode);
    });
}

// Call this method when you detect a master change
private void HandleMasterChange()
{
    // Dispose the existing connection, if any
    if (redisConnection?.IsValueCreated == true)
    {
        redisConnection.Value.Dispose();
    }

    // Recreate the connection
    InitializeRedisConnection();
}

在这个例子中,我添加了一个名为HandleMasterChange的方法,如果已经创建了连接,则会释放现有的连接,然后通过调用InitializeRedisConnection重新创建连接。这样,您的应用程序可以通过在需要时重新创建ConnectionMultiplexer来适应Sentinel中的主节点更改。
重新创建ConnectionMultiplexer通常被认为是一种更清晰和可靠的方法,而不是尝试修改现有的连接。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接