Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
nenj Avatar asked Jan 31 '14 12:01

nenj


People also ask

How does Redis integrate with node js?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.

How do I connect to a Redis database?

To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command. In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.

How does Redis connection work?

Redis accepts clients connections on the configured TCP port and on the Unix socket if enabled. When a new client connection is accepted the following operations are performed: The client socket is put in the non-blocking state since Redis uses multiplexing and non-blocking I/O.


1 Answers

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.

like image 114
Dipen Bhikadya Avatar answered Sep 19 '22 14:09

Dipen Bhikadya