redis sentinel模式下,如何选举新的master

本文介绍了 Redis Sentinel 的工作原理,包括其如何监控 Redis 主从服务的状态,并详细解释了主观失效(S_DOWN)与客观失效(O_DOWN)的概念。此外还阐述了 Redis 2.8.7 版本中故障转移(failover)的触发条件及新 Master 节点的选取算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先要清楚,sentinel是一个独立于redis之外的进程,不对外提供key/value服务。在redis的安装目录下名称叫redis-sentinel主要用来监控redis-server进程,进行master/slave管理,如果你的redis没有运行在master/slave模式下,不需要设置sentinel。

 
两个基本概念
  1. S_DOWN:subjectively down,直接翻译的为"主观"失效,即当前sentinel实例认为某个redis服务为"不可用"状态.
  2. O_DOWN:objectively down,直接翻译为"客观"失效,即多个sentinel实例都认为master处于"SDOWN"状态,那么此时master将处于ODOWN,ODOWN可以简单理解为master已经被集群确定为"不可用",将会开启failover.
redis2.8.7的选举有两个条件,首先是要下面的条件过滤掉一些节点
一、使用如下条件筛选备选node:
1、slave节点状态处于S_DOWN,O_DOWN,DISCONNECTED的除外
2、最近一次ping应答时间不超过5倍ping的间隔(假如ping的间隔为1秒,则最近一次应答延迟不应超过5秒,redis sentinel默认为1秒)
3、info_refresh应答不超过3倍info_refresh的间隔(原理同2,redis sentinel默认为10秒)
4、slave节点与master节点失去联系的时间不能超过( (now - master->s_down_since_time) + (master->down_after_period * 10))。总体意思是说,slave节点与master同步太不及时的(比如新启动的节点),不应该参与被选举。
5、Slave priority不等于0(这个是在配置文件中指定,默认配置为100)。
二、从备选node中,按照如下顺序选择新的master
1、较低的slave_priority(这个是在配置文件中指定,默认配置为100)
2、较大的replication offset(每个slave在与master同步后offset自动增加)
3、较小的runid(每个redis实例,都会有一个runid,通常是一个40位的随机字符串,在redis启动时设置,重复概率非常小)
4、如果以上条件都不足以区别出唯一的节点,则会看哪个slave节点处理之前master发送的command多,就选谁。
附原英文:
Select a suitable slave to promote. The current algorithm only uses
the following parameters:
1) None of the following conditions: S_DOWN, O_DOWN, DISCONNECTED.
2) Last time the slave replied to ping no more than 5 times the PING period.
3) info_refresh not older than 3 times the INFO refresh period.
4) master_link_down_time no more than:
    (now - master->s_down_since_time) + (master->down_after_period * 10).
   Basically since the master is down from our POV, the slave reports
   to be disconnected no more than 10 times the configured down-after-period.
   This is pretty much black magic but the idea is, the master was not
   available so the slave may be lagging, but not over a certain time.
   Anyway we'll select the best slave according to replication offset.
5) Slave priority can't be zero, otherwise the slave is discarded.
Among all the slaves matching the above conditions we select the slave
with, in order of sorting key:
- lower slave_priority
- bigger processed replication offset.
- lexicographically smaller runid.
Basically if runid is the same, the slave that processed more commands
from the master is selected.
runid
 Redis "Run ID", a SHA1-sized random number that identifies a
 given execution of Redis, so that if you are talking with an instance
  having run_id == A, and you reconnect and it has run_id == B, you can be
 sure that it is either a different instance or it was restarte
util.c
void getRandomHexChars(char *p, unsigned int len);

我准备了一些开发防采坑案例,欢迎关注我的公众号

 

 

### Redis Sentinel 模式的配置与工作原理 #### 1. Redis Sentinel 的基本概念 Redis Sentinel 是一种高可用性解决方案,主要用于监控 Redis 主从实例的状态,并在主节点发生故障时执行自动故障转移。这种机制可以显著提高系统的可靠性,确保即使在单点故障的情况下,服务仍能正常运行[^3]。 #### 2. 工作原理详解 Redis Sentinel 的核心功能包括以下几个方面: - **监控 (Monitoring)** Sentinel 节点会持续不断地检查主服务器和从服务器是否按预期工作。如果发现主服务器不可用,则触发后续操作[^1]。 - **通知 (Notification)** 当被监控的某个 Redis 实例现问题时,Sentinel 可以向管理员或其他应用程序发送警报,以便及时采取措施[^2]。 - **自动故障转移 (Automatic Failover)** 如果主服务器无法继续工作,Sentinel 将启动选举流程,选择一个合适的从服务器升级为主服务器,并更新客户端连接信息。 - **配置提供者 (Configuration Provider)** 客户端可以通过 Sentinel 获取当前最新的主服务器地址,从而动态调整自己的连接目标。 #### 3. 配置方法 以下是 Redis Sentinel 的典型配置过程及其关键参数说明: ##### (1)安装与初始化 假设已经部署好 RedisSentinel 所需环境,创建 `sentinel.conf` 文件来定义哨兵的行为规则。以下是一个简单的配置文件示例: ```bash port 26379 # 设置 Sentinel 运行的端口号 daemonize yes # 后台运行 logfile "/var/log/redis/sentinel.log" # 日志路径 dir /tmp # 数据存储目录 # 监控名为 mymaster 的主从集群,其中 master 地址为 127.0.0.1:6379, # 至少需要 2 个 Sentinel 协议确认才能判定主节点下线 sentinel monitor mymaster 127.0.0.1 6379 2 # 故障切换超时时间设置为 180 秒 sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 180000 ``` 上述配置中: - `sentinel monitor`: 表明要监视哪个主库(名称、IP、端口),以及至少多少个 Sentinel 认可该判断才生效。 - `down-after-milliseconds`: 设定多长时间未收到回复视为断开链接。 - `failover-timeout`: 控制整个故障转移的最大允许耗时时长。 ##### (2)启动多个 Sentinel 实例 为了增强健壮性,通常建议在同一网络环境下部署三个或更多 Sentinel 实例形成多数派决策机制。每个 Sentinel 使用相同的配置文件即可独立运行。 命令如下所示: ```bash redis-sentinel /path/to/sentinel.conf ``` #### 4. 自动故障转移的具体流程 当主服务器宕机后,Sentinel 群体会按照既定逻辑完成以下步骤: 1. 多数 Sentinel 达成一致意见认为原 Master 不再可达; 2. 在存活 Slave 中挑选最适合作为新 Master 的候选对象; 3. 更新所有 Client 对应的新 Master IP 和 Port; 4. 修改其他 Slaves 关联关系使其同步到新的 Master 上。 --- ### 示例代码:验证 Sentinel 功能的小型 Python 应用程序 下面展示如何利用 redis-py 库编写一段脚本测试 Sentinel 是否成功接管失败的服务。 ```python import redis from redis.sentinel import Sentinel def connect_to_redis_sentinel(): sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1) master = sentinel.master_for('mymaster', db=0, password=None, socket_timeout=0.1) try: result = master.set('test_key', 'value') value = master.get('test_key').decode() print(f"Successfully set key with value {value}") except Exception as e: print("Error occurred:", str(e)) if __name__ == "__main__": connect_to_redis_sentinel() ``` 此段代码展示了通过 Sentinel API 来获取当前有效的 Master 并尝试写入数据的过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值