简体   繁体   中英

Node.js server: connect to redis database once? or at each request?

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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM