Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (re-)use redis client connections in nodejs/express?

Given a simple example:

var express = require("express")
var redis = require('redis')
var app = express()

var client = redis.createClient()

app.get('/', function(req, res) {
    req.connection.setTimeout(2 * 1000)
    client.set("test", 1, function (err, resp) {
        res.send('Hello World')
    })
})

app.listen(80)

Redis connection doesn't need to be re-established for every request, does it?

Do you need to use redis connection pool?

like image 901
Bdfy Avatar asked Apr 30 '13 08:04

Bdfy


People also ask

How use Redis node JS Express?

To use the Redis, you need to install Node JS Redis Client in the local system. The msi file (v3. 0.504 stable version as of this article published date) can be downloaded from the Github and proceed with normal installation process (for Windows OS).

Should I reuse Redis connection?

Redis connection instance is single-threaded. If we reuse a single Redis connection between multiple threads, it may not be enough to complete the required tasks in a limited time. If we create a separate Redis connection for a thread it will be overhead for the Redis server.

How do I connect to a node js server in Redis?

Use a connection string to your remote Redis DB to connect to a different host or port. The connect() method is used to connect the NodeJS to the Redis Server. This return promise that's why we have to handle it either using the then and catch or using the sync and await keyword.

Can Redis handle multiple connections?

Redis can handle many connections, and by default, Redis has a maximum number of client connections set at 10,000 connections. You can set the maximum number of client connections you want the Redis server to accept by altering the maxclient from within the redis. conf file.


1 Answers

Replying to incarnate's connection pool post:

Hi there -- first clarification, Redis server IS single-threaded.

What you're seeing in terms of command ordering is an artifact of the way you're using async, and unrelated to either node_redis library or Redis itself.

Connection pooling with node_redis is definitely not required. You can certainly use it, but it is not suggested. Connection pooling will reduce the effectiveness of Redis pipelining, and due to the stateful nature of the Redis protocol, can be problematic with some commands.

Reason #1: I'm not sure this is significant, or possibly worse by creating additional clients which are an additional GC burden.

Reason #2: That's not really how it works. The Redis server is single-threaded. If you're waiting on the server, all clients are waiting on the server. If you're blocked in javascript, all clients in that process are blocked in javascript.

Reason #3: The node_redis library already reconnects after failures.

like image 136
Bryce Baril Avatar answered Sep 19 '22 02:09

Bryce Baril