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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With