Search code examples
node.jsredisnode-redisredis-sentinel

Identifying Redis Master using sentinal from nodeJS


I have 2 Redis servers one master and the other slave(replication). Once the Master is down due to some reasons the slave will become Master and it continues to act as Master till something wrong happens to that server.

I have a nodeJS server from which i want to push data to the Redis which currently running as Master. I have a sentinel which monitors the Redis servers but my question is how to fetch master information from sentinel using nodeJS? and if there is a way, does it automatically push data to alternative redis server without any service restart?


Solution

  • The ioredis supports the sentinel. like this:

    var redis = new Redis({
      sentinels: [{ host: 'localhost', port: 26379 }, { host: 'localhost', port: 26380 }],
      name: 'mymaster'
    });
    
    redis.set('foo', 'bar');
    

    The name identifies a redis cluster, which you should also specified in redis sentinel.conf. You could refer this page on how to configure sentinel.

    About your second question, see below:

    ioredis guarantees that the node you connected to is always a master even after a failover. When a failover happens, instead of trying to reconnect to the failed node (which will be demoted to slave when it's available again), ioredis will ask sentinels for the new master node and connect to it. All commands sent during the failover are queued and will be executed when the new connection is established so that none of the commands will be lost.

    And node-redis does not support it now.