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'))How it works
Count the functions cache_get, cache_set and current_topology as the entire surface area of Redis Sentinel Failover Client.
Sentinel are the only symbols borrowed from redis — the coupling is explicit and narrow.
It builds and returns a fresh value rather than reusing its inputs.
What to watch for
- Dependency check:
redis— not built-in, must be present in the project.
Putting it to use
The primary signature is def cache_get(key: str) -> str | None
Running the file prints labeled results such as topology:, read back: — each operation’s effect is visible in the output.
cache_get is the public entry point; everything else in the file exists to support it.
Core lines
def cache_get(key: str) -> str | None:
try:
return replica.get(key) # 读走副本,减轻主库压力
except (redis.ConnectionError, redis.TimeoutError):
return master.get(key) # 副本不可用时回退主库
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],
}
except redis.ConnectionError:
# 哨兵可能正在切换,稍等后重新解析主节点地址
time.sleep(0.2)
fresh = sentinel.master_for('mymaster', socket_timeout=1.0)
fresh.set(key, value, ex=ttl)
return True
Interactive Tools for This Topic
FAQ
- Does `cache_get` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Which packages must be installed first?
- Yes. The imports resolve to `redis`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.