How to create redis python client from sentinel url?

Nilesh picture Nilesh · Aug 25, 2017 · Viewed 8.9k times · Source

I have url as

BROKER_URL = 'sentinel://192.168.10.1:26379/0;sentinel://192.168.10.2:26379/0;sentinel://192.168.10.3:26379/0'

In this, redis is running on 192.168.10.1, 192.168.10.2 and 192.168.10.3. One node is master and others are slaves. If master went down, other node take place for master.

I check the redis client but it has no method, where we can provide url like I gave.

We have to provide hostname and port. In my case, master will be anyone form these 3.

Answer

GuangshengZuo picture GuangshengZuo · Aug 25, 2017

Check the redis-py codebase readme.md at https://github.com/andymccurdy/redis-py/blob/master/README.rst#sentinel-support

Like this:

from redis.sentinel import Sentinel
sentinel = Sentinel([('192.168.10.1', 26379), ('192.168.10.2',26379), ('192.168.10.3',26379)], socket_timeout=0.1)

master = sentinel.master_for('master-name', socket_timeout=0.1)

The master and slave objects are normal StrictRedis instances with their connection pool bound to the Sentinel instance. When a Sentinel backed client attempts to establish a connection, it first queries the Sentinel servers to determine an appropriate host to connect to. If no server is found, a MasterNotFoundError or SlaveNotFoundError is raised.

The Actual thing is that if you build Sentinel for redis cluster, you do not need to connect the redis server directly. Do as above, first connect to Sentinel, and use master_for to query the an appropriate host to connect to. Only in this way, if master is down, your client could be directed to the new master.

And The master-name in the code above, you should specify in the sentinel.conf in

sentinel monitor <master-group-name> <ip> <port> <quorum>

like this:

sentinel monitor mymaster 127.0.0.1 6379 2