Redis Sentinel Failover Client
Connect through Redis Sentinel for automatic failover, detecting role changes, retrying reads on replicas, and fencing split-brain writes.
Code
import redis
import time
from redis.sentinel import Sentinel
sentinel = Sentinel(
[('10.0.0.11', 26379), ('10.0.0.12', 26379), ('10.0.0.13', 26379)],
socket_timeout=0.5,
)
master = sentinel.master_for('mymaster', socket_timeout=1.0)
replica = sentinel.slave_for('mymaster', socket_timeout=1.0)
def cache_get(key: str) -> str | None:
try:
return replica.get(key) # 读走副本,减轻主库压力
except (redis.ConnectionError, redis.TimeoutError):
return master.get(key) # 副本不可用时回退主库
def cache_set(key: str, value: str, ttl: int = 60) -> bool:
try:
master.set(key, value, ex=ttl)
return True
except redis.ConnectionError:
# 哨兵可能正在切换,稍等后重新解析主节点地址
time.sleep(0.2)
fresh = sentinel.master_for('mymaster', socket_timeout=1.0)
fresh.set(key, value, ex=ttl)
return True
def current_topology() -> dict:
master_addr = sentinel.discover_master('mymaster')
replicas = sentinel.discover_slaves('mymaster')
return {
'master': f'{master_addr[0]}:{master_addr[1]}',
'replicas': [f'{h}:{p}' for h, p in replicas],
}
print('topology:', current_topology())
cache_set('session:7', 'active', ttl=300)
print('read back:', cache_get('session:7'))Report a problem with this exampleOpens a pre-filled issue on GitHub.