【问题标题】:Redis Connection CheckRedis 连接检查
【发布时间】:2019-11-12 21:57:12
【问题描述】:

我是 Azure Redis Cache 的新手。我正在尝试在将数据写入之前检查客户端变量的连接。 如何在 Nodejs 中实现这一点?

我尝试获取 client.connected 状态,但是当我进行负面测试时 - 例如关闭 redis 服务器,client.connected 变量没有收到任何内容,因此我的代码没有进一步获取 eh 数据从我的原始服务器,通过缓存服务器。

如何在 nodejs 中做到这一点?

【问题讨论】:

标签: node.js redis node-redis


【解决方案1】:

redis 有一个PING 命令。你可以试试redis.ping()检查redis服务器连接是否正常

来自 redis 文档:

如果没有提供参数,则返回 PONG,否则将参数的副本作为批量返回。此命令通常用于测试连接是否仍然有效,或测量延迟。

如果客户端订阅了频道或模式,它将改为返回一个多批量,其中第一个位置是“pong”,第二个位置是空批量,除非提供了参数,在这种情况下它返回参数的副本。

【讨论】:

    【解决方案2】:

    为了在使用redis npm 包时进行可靠的连接检查,您应该使用重试逻辑,处理就绪事件,并在必要时 ping 到内脏检查。

    重试

    在创建客户端时,自动有一个默认重试策略,但是您可以传入options objectretry_strategy 来自定义它:

    const client = require('redis').createClient({
    
      retry_strategy: function(options) {
        if (options.error && options.error.code === "ECONNREFUSED") {
          // End reconnecting on a specific error
          return new Error("The server refused the connection");
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
          // End reconnecting after a specific timeout
          return new Error("Retry time exhausted");
        }
        if (options.attempt > 10) {
          // End reconnecting with built in error
          return undefined;
        }
    
        // reconnect after
        return Math.min(options.attempt * 100, 3000);
      },
    
    });
    

    准备好了

    创建客户端后,您应该先监听connection and other events,然后再进行如下操作:

    var client = require('redis').createClient();
    
    client.on('connect'     , () => console.log('connect'));
    client.on('ready'       , () => console.log('ready'));
    client.on('reconnecting', () => console.log('reconnecting'));
    client.on('error'       , () => console.log('error'));
    client.on('end'         , () => console.log('end'));
    

    正如redis包文档中提到的,在节点客户端和official redis commands之间有一个1 to 1 mapping of commands,所以你可以像这样调用ping来做一个最终的冒烟测试:

    var client = require('redis').createClient();
    
    client.on('ready', () => {
        let response = client.ping()
        console.log(response)
        // do other stuff
    });
    

    进一步阅读

    【讨论】:

      【解决方案3】:

      来自npm docs

      “准备好了”

      一旦建立连接,客户端就会发出就绪信号。命令 在就绪事件排队之前发出,然后在之前重播 发出此事件。

      所以这可以通过下面的sn-p来实现:

      const redis = require("redis");  
      const client = redis.createClient();
      
      client.on("ready", function() {  
        console.log("Connected to Redis server successfully");  
      });
      

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 2011-09-30
        • 2020-01-30
        • 2021-03-13
        • 2013-02-19
        • 2022-11-07
        • 2012-11-06
        • 2018-09-06
        • 2018-09-29
        相关资源
        最近更新 更多