在redis安装后,会自带sentinel哨兵程序,修改sentinel.conf配置文件
bind 127.0.0.1
port 26380
daemonize yes
logfile /var/log/redis-sentinel.log
sentinel monitor mymaster 127.0.0.1 6380 2
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel monitor mymaster 127.0.0.1 6380 2 说明
mymaster 为sentinel监护的redis主从集群起名
127.0.0.1 6300 为主从中任一台机器地址
2 表示有两台以的sentinel认为某一台redis宕机后,才会进行自动故障转移。
启动方式:
redis-sentinel sentinel.conf
高可用方案注意事项
至少三个sentinel以上
sentinel要分散运行在不同的机器上
# redis 哨兵
REDIS_SENTINELS = [
('127.0.0.1', '26380'),
('127.0.0.1', '26381'),
('127.0.0.1', '26382'),
]
REDIS_SENTINEL_SERVICE_NAME = 'mymaster'
from redis.sentinel import Sentinel
_sentinel = Sentinel(REDIS_SENTINELS)
redis_master = _sentinel.master_for(REDIS_SENTINEL_SERVICE_NAME)
redis_slave = _sentinel.slave_for(REDIS_SENTINEL_SERVICE_NAME)
# 读数据,master读不到去slave读
try:
real_code = redis_master.get(key)
except ConnectionError as e:
real_code = redis_slave.get(key)
# 写数据,只能在master里写
try:
current_app.redis_master.delete(key)
except ConnectionError as e:
logger.error(e)
参考:
https://www.cnblogs.com/pinghengxing/p/11139997.html