nodejs redis 连接恢复(服务器运行时)

时间:2021-05-27 20:18:36

标签: node.js redis node-redis

我使用 nodejs 和 redis 库来初始化客户端。

我想问一下在某些场景下如何处理redis连接。服务器启动时,我知道有一个重试配置选项。我配置了 10 次尝试和每次尝试之间的等待时间。

我怀疑服务器运行后恢复连接的最佳方法是什么。例如,服务器启动并成功连接到 redis 客户端,但之后我的 redis-server 出现故障。如何在不重启服务器的情况下恢复连接?

这里是我的 redis/client.js 文件。如果您对实际应用中的此实现有任何建议,欢迎提出!

'use strict';

const redis = require('async-redis');
var retryStrategy = require("node-redis-retry-strategy");

const client = redis.createClient(process.env.REDIS_PORT_DEV, process.env.REDIS_HOST_DEV, {
        retry_strategy: function(options) {
            if (options.total_retry_time > 1000 * 60 * 60) {
              // End reconnecting after a specific timeout and flush all commands
              // with a individual error
              strapi.log.error("ERR:REDIS: Retry time exhausted"); // ctx.log.info(folders);
              return new Error("Retry time exhausted");
            }

            if (options.attempt > 10) {
              // End reconnecting with built in error
              strapi.log.error("ERR:REDIS: Connection with REDIS failed after 10 attempts"); // ctx.log.info(folders);
              return undefined;
            }

            // reconnect after
            return Math.min(options.attempt * 100, 3000);
        }
    },
);

client.on("connect", function(time, args, rawReply) {
  strapi.log.info("Connected to Redis")
});

client.on("reconnecting", function (o) {
    strapi.log.info("Redis client reconnecting", o.attempt, o.delay);
});

client.on("end", function () {
    strapi.log.info("redis connection has closed");
});

client.on("monitor", function(time, args, rawReply) {
  strapi.log.info(time + ": " + args);
});

client.on('error', err => strapi.log.error('ERR:REDIS:', err));

const defaultExpirationTime = 6000; //second

module.exports = {

  async set(key, value, expirationTime){
    try{
        await client.setex(key, expirationTime || defaultExpirationTime, value);
    } catch (err) {
        strapi.log.error(`ERR:REDIS: Error in ${err.command} operation:`, err.code)
        return undefined;
    }
  },

  async fetch(key){
    try{
        return await client.get(key);
    } catch (err) {
        strapi.log.error(`ERR:REDIS: Error in ${err.command} get operation:`, err.code)
        return undefined;
    }
  },

  async clear(key){
    try{
        return await client.del(key);
    } catch (err) {
        strapi.log.error(`ERR:REDIS: Error in ${err.command} operation:`, err.code)
        return undefined;
    }
  },

}

谢谢!

0 个答案:

没有答案