I am trying to find the best practice to use redis client with express server, for somehow I don’t know whether to create a redis client each time or reuse the global redis client.
The first method is to create only one redis client, reuse it in each request.
const redis = require("redis").createClient();
function createExample(req, res){
try {
await redis.connect();
... to do more
} catch(err) {
console.log("Err:", err);
}
await redis.disconnect();
req.json({'msg':'success'});
}
The second example is to create redis client every time the request comes.
function createExample2(req, res){
const redis = require("redis").createClient();
try {
await redis.connect();
... to do more
} catch(err) {
console.log("Err:", err);
}
await redis.disconnect();
req.json({'msg':'success'});
}
which method is more reasonable, any idea?
2
Answers
I always create a single connection. I have two reasons:
Redis connections are not free to create. Creating one for each call is significantly slower. Keeping one around makes for faster responses.
Both Node.js and Redis are single-threaded. Given Redis’ quick response times, there typically isn’t more than one thing at a time in a Node.js process trying to get to Redis. And if there is—say because your code is waiting on a response from a long-running Redis command, the type of commands that should be avoid anyhow—it couldn’t do anything anyhow as it would have to wait on the single thread in Redis.
There are certainly exceptions to this, but I think for most cases, this is the way to go. I wouldn’t go so far as to say that this is the official stance of Redis, but I work for them as a developer advocate and this is how I build all my sample code.
It depends. I would suggest re-using the same single connection to Redis if the code obeys these rules:
SELECT
and everything else mentioned here);In all the other cases, using dedicated connections may be a better option.