【问题标题】:Establish 'connection retry' behaviour on start-up even when Redis is not available即使 Redis 不可用,也要在启动时建立“连接重试”行为
【发布时间】:2017-08-23 10:13:30
【问题描述】:

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

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

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

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

我可以编写代码来重试初始 Redis 连接直到它成功,但让我感到震惊的是,现成可用的功能已经非常接近我需要的功能,如果我能说服它来的话即使 Redis 宕机,从一开始就开始发挥作用。

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    retry_strategy 实际上可以以毫秒为单位返回一个数字,以尝试在该时间之后重试连接。如果在您的节点启动时连接已关闭,您可以简单地返回例如5000 当错误代码为 NR_CLOSED 或 ECONNREFUSED 时让它在 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});
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 但是即使Redis在启动时不可用,它会尝试像这样重新连接吗?
      • 它确实在他们的文档中说它会继续尝试重新连接,您可以通过收听github.com/NodeRedis/node_redis#reconnecting中提到的重新连接事件来测试这一点
      • 尝试连接离线服务器并监听reconnecting事件进行验证
      猜你喜欢
      • 2015-09-12
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多