Node.js: Closing all Redis clients on shutdown
javascript, node-redis, node.js, redis
Solution
In terms of design and performance, it's best to create one client and use it across your application. This is pretty easy to do in node. I'm assuming you're using the `redis` npm package.
First, create a file named `redis.js` with the following contents:
const redis = require('redis');
const RedisClient = (function() {
return redis.createClient();
})();
module.exports = RedisClient
Then, say in a file `set.js`, you would use it as so:
const client = require('./redis');
client.set('key', 'value');
Then, in your `index.js` file, you can import it and close the connection on exit:
const client = require('./redis');
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
function cleanup() {
client.quit(function() {
console.log('Redis client stopped.');
server.stop(function() {
console.log('Server stopped.');
process.exit();
});
});
};
Problem
Today, I integrated Redis into my node.js application and am using it as a session store. Basically, upon successful authentication, I store the corresponding user object in Redis. When I receive http requests after authentication, I attempt to retrieve the user object from Redis using a hash. If the retrieval was successful, that means the user is logged in and the request can be fulfilled. The act of storing the user object in Redis and the retrieval happen in two different files, so I have one Redis client in each file. Question 1: Is it ok having two Redis clients, one in each file? Or should I instantiate only one client and use it across all areas of the application? Question 2: Does the node-redis library provide a method to show a list of connected clients? If it does, I will be able to iterate through the list, and call client.quit() for each of them when the server is shutting down. By the way, this is how I'm implementing the "graceful shutdown" of the server: ``` //Gracefully shutdown and perform clean-up when kill signal is received process.on('SIGINT', cleanup); process.on('SIGTERM', cleanup); function cleanup() { server.stop(function() { //todo: quit all connected redis clients console.log('Server stopped.'); //exit the process process.exit(); }); }; ```