Ioredis:通过 connect() 重新连接 redis 时,调用 connect 不会将重试次数重置为 0

Ioredis: When reconnecting redis via connect() , calling connect doesn't reset retry times to 0

我在连接到 Redis 时设置了以下选项

var client = new Redis({
  port: 63xx, // Redis port
  host: REDISHOST, // Redis host
  family: 4, // 4 (IPv4) or 6 (IPv6)
  db: 0,
  lazyConnect: true,
  // The milliseconds before a timeout occurs during the initial connection to the Redis server.
  connectTimeout: 3000,

  retryStrategy: function (times) {

    if (times > 3) {
      logger.error("redisRetryError", 'Redis reconnect exhausted after 3 retries.');
      return null;
    }

    return 200;

  }

}); 

稍后,我将在整个项目中导出此客户端以进行 redis 查询。 问题是当 Request 1 出现并且 redis 出现问题时,它会尝试自动连接 4 次(初始尝试 +1)。然后抛出已处理的错误。 所以现在时间变量(在 retrystrategy() 中使用)将具有 4 作为值。

下一次 请求 2 到来时,我们看到 redis 已断开连接,因此我们使用 client.connect() 方法重新连接:

static async getData(key) {

        try {

            // if connection is ended then we are trying to reconnect it.
            if (client.status === 'end') {
                await logger.warning(`reconnectingRedis`, 'Redis is not connected. Trying to reconnect to Redis!');
                await client.connect();
            }

            let output = await client.get(key);

            return JSON.parse(output);

        } catch (error) {
            ApiError.throw(error, errorCode.REDIS_GET_ERROR_CODE);
        }

    }

这次 redis 尝试重新连接,但它没有重置 retrystrategy() 中使用的时间变量,所以这个变量现在有 5。 如果这次尝试也失败了,retrystrategy() 只会抛出错误 times > 3

如此有效 请求 1 得到 4 次尝试而 请求 2 只得到 1

我该如何解决这个问题,以便 请求 2 也得到 4 次尝试?

为了解决这个问题,我按以下方式更改了创建 redis 时使用的 retryStrategy 函数:

retryStrategy: function (times) {

    if (times % 4 ==0) { 
      logger.error("redisRetryError", 'Redis reconnect exhausted after 3 retries.');
      return null;
    }

    return 200;

  }

注意 我取了 mod 4 次变量并且这样做我们总是会得到一个在 0-3 范围内的值。

所以对于request 2,当times变量有5时,它的mod 4会给出1并且会被尝试, 下次 times 将是 6,所以 mode 4 是 2 并且将被尝试等等。直到它变成 8,在这种情况下,mod 4 将给出 0 并重试停止。

这解决了我的问题。