Monday, 28 June 2021

Redis Sentinel: How to refresh master client object when master changes on failover?

I have setup a Redis replica with one master and two slaves with Redis Sentinel monitoring each of the nodes. I'm using redis-py library to communicate with master and slaves. Here is the code that I use to connect with master and slaves:

from redis.sentinel import Sentinel

sentinel = Sentinel([("localhost", 5000)])  # connect to one of the sentinels
master = sentinel.master_for("mymaster")  # get master object
slave = sentinel.slave_for("mymaster")  # get slave object

Now, I would use master for write and slave for reads. But the problem is that when failover occurs, the master object needs to be refreshed in order to point to a new master. For that, as mentioned in this answer and the docs, I'm supposed to subscribe on +switch-master channel to receive the address of new master.

But the questions is that, using which object am I supposed to subscribe to that channel? I tried this using master object as following:

ps = master.pubsub()
ps.subscribe("+switch-master")

And when the master was down, I tried getting the message as following:

ps.get_message()

But this does not return the expected message because the master itself is down I think.

The sentinel object does not support the pubsub.

>>> sentinel.pubsub()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Sentinel' object has no attribute 'pubsub'

As an alternative, in the linked answer it's suggested to use client-reconfig-script. But how am I supposed to modify an object in my application using an external script?

What am I missing here? I am new to Redis, so any reference would be appreciated.



from Redis Sentinel: How to refresh master client object when master changes on failover?

No comments:

Post a Comment