gpt4 book ai didi

redis - 在集群中选举出新的 master 时恢复连接

转载 作者:IT王子 更新时间:2023-10-29 06:07:29 25 4
gpt4 key购买 nike

我有一个包含 3 个节点的 Redis 集群; 1个是master,另外2个是slave,持有master的副本。当我杀死 master 实例时,Redis Sentinel 将另一个节点提升为 master,它开始接受写入。

在我的测试过程中,我注意到一旦提升了新的 master,Redis 中使用 SE.Redis 的第一个操作就会失败:

StackExchange.Redis.RedisConnectionException: SocketFailure on GET ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

为了避免这种情况,我实现了如下重试逻辑。有没有更好的选择?

private RedisValue RedisGet(string key)
{
return RedisOperation(() =>
{
RedisKey redisKey = key;
RedisValue redisValue = connection.StringGet(redisKey);
return (redisValue);
});
}

private T RedisOperation<T>(Func<T> act)
{
int timeToSleepBeforeRetryInMiliseconds = 20;
DateTime startTime = DateTime.Now;

while (true)
{
try
{
return act();
}
catch (Exception e)
{
Debug.WriteLine("Failed to perform REDIS OP");

TimeSpan passedTime = DateTime.Now - startTime;
if (this.retryTimeout < passedTime)
{
Debug.WriteLine("ABORTING re-try to REDIS OP");
throw;
}
else
{
int remainingTimeout = (int)(this.retryTimeout.TotalMilliseconds - passedTime.TotalMilliseconds);
// if remaining time is less than 1 sec than wait only for that much time and than give a last try
if (remainingTimeout < timeToSleepBeforeRetryInMiliseconds)
{
timeToSleepBeforeRetryInMiliseconds = remainingTimeout;
}
}

Debug.WriteLine("Sleeping " + timeToSleepBeforeRetryInMiliseconds + " before next try");
System.Threading.Thread.Sleep(timeToSleepBeforeRetryInMiliseconds);
}
}
}

最佳答案

TLDR:不要将 Sentinel 与 Stackexchange.Redis 一起使用,因为此客户端库中仍未实现 Sentinel 支持。

参见 https://github.com/StackExchange/StackExchange.Redis/labels/sentinel对于所有 Unresolved 问题,还有一个相当不错的 PR 开放了大约 1 年。

话虽如此,我在重试方面也有相对较好的经验,但我绝不会在生产中使用这种方法,因为它根本不可靠。

关于redis - 在集群中选举出新的 master 时恢复连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44554571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com