Redis哨兵模式原理
Redis哨兵工作原理可以概括为3个阶段监控阶段,通知阶段,故障转移阶段。全部是文字,比较枯燥。
监控阶段
一个Sentinel的监控行为
Sentinel1 向master发送info
master返回info信息给Sentinel 1
Sentinel1 与master建立cmd连接
Sentinel1 向所有slave发送info
Sentinel1 记录SentinelState(包括master,slave,sentinels )
master记录SentinelRedisInstance(包括master,slave,sentinels )
Sentinel集群行为
所有Sentinel互相ping,比如Sentinel2 与 Sentinel1 互相ping
所有Sentinel 互相publish 和subscribe 同步最新的Redis节点信息
监控阶段总结:
Sentinel 会向master,slave以及其他Sentinel 获取状态;
Sentinel 之间会组建“频道”,订阅消息,发布消息,收集消息,同步消息
通知阶段
信息的长期维护阶段
一个Sentinel行为
某个时间点Sentinel1向所有redis节点发送hello消息 publish sentinel hello,检测各个节点的状态
Sentinel集群行为
Sentinel 集群之间会把其中一个Sentinel获取的消息互相同步
通知阶段总结
Sentinel 集群之间信息的长期维护阶段
故障转移阶段
故障发现
一个Sentinel行为
某个时间点Sentinel1向master节点发送hello消息 ,master没有回应; Sentinel1重复向master发送hello多次后,master还是没反应; SentinelRedisInstance记录master为s_down;(主观下线)
Sentinel1向其他Sentinel同步消息
Sentinel集群行为
Sentinel1向集群所有Sentinel进行master挂了的消息同步;
其他Sentinel收到消息后,主动向master重复发送hello消息,确认master挂了,相当于重复上边标题一个Sentinel行为;
超过半数的Sentinel认为master挂了的话;SentinelRedisInstance中记录master为s_down会变成o_down;(客观下线)
选举Sentinel代表
一个Sentinel行为
一个Sentinel 发送自己竞选次数,runid
Sentinel集群行为
Sentinel集群通过多次竞选选出Sentinel代表;
Sentinel代表从slave列表选择一个作为master
选择标准:
在线的slave;响应较快的slave;与原master断开时间较长的slave;按照优先原则(优先级,偏移量,runid等)
被选择的slave变为新的master
Sentinel向新的master发送指令slaveof no one,你不再是一个slave了;
Sentinel向其他slave发送slaveof 新的master ip:port;
原master恢复后作为slave继续工作