Schrute
Schrute

Reputation: 731

Node.js / Redis - Wait for connection?

I'm developing an application in Node.js that uses Redis as its main database and falls back to MySQL when Redis is not available.

The problem I'm having is that, differently from node-mysql, node_redis doesn't accept a callback on the createClient() method and it just emit an error in case it fails.

How can I structure my code to deal with this?

What I need is basically this (pseudo-code):

if can_connect_on_redis
    use_redis
else
    if can_connect_mysql
       use_mysql
    else
       fail
    end
end

Upvotes: 1

Views: 3793

Answers (1)

robertklep
robertklep

Reputation: 203231

Untested:

var client  = redis.createClient();
var isReady = false;
var isError = false;

client.on('error', function() {
  if (! isReady && ! isError) {
    // perform your MySQL setup here
  }
  isError = true;
}).on('ready', function() {
  isReady = true;
});

The idea being that when you get an error before the client is ready, you can assume that the connection to Redis failed and you can fall back to using MySQL. Because the client will try to reconnect, it will keep generating error events, hence the isError guard.

If you want to fall back to MySQL after the client was (succesfully) able to set up a connection (for instance, when the Redis server is stopped), you can remove the isReady logic.

Upvotes: 4

Related Questions