Reputation: 119
I'm building a node.js server, with a simple authentication fetching uid and key in a redis database. Should I connect to the redis db once and for all upon running the server, like:
var http = require('http'),
express = require('express');
var app = express();
var redis = require('redis'),
redisclient = redis.createClient();
//... redis ready, error, end callback handlers here ...
app.get( '/connect/:uid/:key', function(req,res,next) {
redisclient.hget(req.params.uid,req.params.key, function(err,rep) {
// ... commands here...
});
});
or should I connect each time a connection request is done, like so:
var http = require('http'),
express = require('express');
var app = express();
var redis = require('redis');
app.get( '/connect/:uid/:key', function(req,res,next) {
var redisclient = redis.createClient();
//... redis callback handlers here...
redisclient.hget(req.params.uid,req.params.key, function(err,rep) {
// ... commands here...
});
});
?
For now I'm talking about a limited number of connections, sparse in time, and no worries about efficiency optimisation.
Upvotes: 6
Views: 2723
Reputation: 3320
I had the same confusion at some point but couldn't find any good answer. At the end I chose connecting just once to reduce lines of code. Redis mostly follows single threaded design so connection pooling won't be much help either.
Upvotes: 1
Reputation: 2613
You should not do both... Ideally you should have a connection pool.. Lets say 20 connection pool which should be reused.
If you connect on every request then its not good performance wise and also many TCP connection from your application to redis will be in TIMEWAIT status even if you close them.
If you have only one connection then its like you are driving a car on single lane road where network will get conjusted
I am not very sure but I think hiredis (node module) has connection pooling...
Upvotes: 0