For robust connection checking when using the redis
npm package, you should use retry logic, handle the ready event, and ping to gut check if necessary.
Retry
When creating the client, there is automatically a default retry strategy, however you can pass in options object with retry_strategy
to customize it like this:
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);
},
});
Ready
After creating a client, you should listen for connection and other events before proceeding like this:
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'));
Ping
As mentioned in the redis package docs, there is a 1 to 1 mapping of commands between the node client and the official redis commands, so you can do a final smoke test by calling ping
like this:
var client = require('redis').createClient();
client.on('ready', () => {
let response = client.ping()
console.log(response)
// do other stuff
});
Further Reading