Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reconnect redis connection?

Tags:

node.js

I have simple example:

var redis = require('redis'),
client = redis.createClient();

var test = function() {
    client.brpop('log', 0, function(err, reply) {
        if (err != null ) {
            console.log(err);
        }    else {
            .... parse log string ....
        }
        test();
    });
}

test();

How to reconnect redis connection after restart redis server ?

like image 437
Bdfy Avatar asked Jun 04 '12 09:06

Bdfy


1 Answers

The Redis client automatically reconnects. Just make sure you handle the "error" event from the client. As per the example:

var redis = require('redis');
client = redis.createClient();
client.on('error', function(err){ 
  console.error('Redis error:', err); 
});

Otherwise, this code is where the process begins.

this.emit("error", new Error(message));
// "error" events get turned into exceptions if they aren't listened for.  If the user handled this error
// then we should try to reconnect.
this.connection_gone("error");

Next, the .connection_gone() method runs on the client.

Notice that you can also listen to a "reconnecting" event to be notified when this happens.

like image 78
JasonSmith Avatar answered Sep 24 '22 03:09

JasonSmith