I have following options set when connecting to 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;
}
});
Later on, I am exporting this client throughout project for redis queries. The issue is when Request 1 comes and there is some issue with redis, it tries to auto-connect for 4 times(+1 for initial try). Then throws error which is handled. So for now times variable(used in retrystrategy()) will have 4 as value.
Next time when Request 2 comes and we see redis is disconnected so we reconnect using client.connect() method:
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);
}
}
this time redis tries to reconnect but it doesn't resets the times variable used in retrystrategy(), So this variable now have 5.
And if this attempt too fails, retrystrategy() just throws error as times > 3
So effectively Request 1 gets 4 tries and Request 2 gets only 1
How can I fix this, So that Request 2 also gets 4 tries ?