在启动时建立“连接重试”行为,即使 Redis 不可用

问题描述 投票:0回答:3

node-redis
具有出色的功能,可在一切启动并运行后处理任何 Redis 断开连接。如果 Redis 实例变得不可用,使用适当的
retry_strategy
意味着可以将客户端设置为尝试重新连接,直到 Redis 再次可用。

有没有可能让客户端在启动时进入这个状态,即使Redis宕机了?

我的场景是这样的:我将 Redis 用作主要数据存储,并使用不基于 Redis 的后备辅助数据存储。当我的应用程序启动时,如果 Redis 不可用,则尝试检索数据将改用辅助数据存储。

但是,当 Redis 可用时,我希望我的应用程序开始使用 Redis 主数据存储。由于 Redis 连接在启动时没有成功,因此为先前建立的连接处理此问题的

retry_strategy
不起作用。

我可以编写代码来重试初始 Redis 连接,直到成功为止,但令我印象深刻的是,开箱即用的功能已经非常接近我需要的功能,如果我能说服它发挥作用的话即使 Redis 宕机了,也会从启动开始。

node.js redis node-redis
3个回答
13
投票

retry_strategy 实际上可以以毫秒为单位返回一个数字 以尝试在该时间之后重试连接。如果连接在您的节点启动时关闭,您可以简单地返回例如当错误代码为 NR_CLOSED 或 ECONNREFUSED 时为 5000,使其在 5 秒后重试。

例子:

const retry_strategy = function(options) {
    if (options.error && (options.error.code === 'ECONNREFUSED' || options.error.code === 'NR_CLOSED')) {
        // Try reconnecting after 5 seconds
        console.error('The server refused the connection. Retrying connection...');
        return 5000;
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
        // End reconnecting after a specific timeout and flush all commands with an individual error
        return new Error('Retry time exhausted');
    }
    if (options.attempt > 50) {
        // End reconnecting with built in error
        return undefined;
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000);
}

并使用此重试策略创建客户端:

const client = redis.createClient({retry_strategy: retry_strategy});

6
投票

默认情况下,客户端将尝试重新连接直到连接。如果你想自定义它,你可以使用选项object properties中可用的retry_strategy。你可以知道 redis 何时连接,因为它会发出一个事件

client.on("connect", function (){
});

您可以稍后决定连接后如何处理


0
投票

在客户端选项的套接字部分使用 reconnectStrategy。 在下面的示例中使用指数退避

 const maxConnectRetry = 10
 const minConnectDelay = 100; // Milliseconds
 const maxConnectDelay = 60000; // Milliseconds
 
 const client = redisObj.createClient({
    socket: {
        host: host,
        port: port,
        connectTimeout: 5000,
        reconnectStrategy: (retries) => {
            if (retries > maxConnectRetry) {
                console.log("Too many retries on REDIS. Connection Terminated");
                return new Error("Too many retries.");
            } else {
                const wait = Math.min(minConnectDelay * Math.pow(2, retries), maxConnectDelay);
                console.log("waiting", wait, "milliseconds");
                return wait;
            }
        }
    },
    database: dbIndex
});
© www.soinside.com 2019 - 2024. All rights reserved.