(集群)Sentinel哨兵模式
4Sentinel哨兵模式
4.1主从模式的缺陷
当主节点宕机了,整个集群就没有可写的节点了。
由于从节点上备份了主节点的所有数据,那在主节点宕机的情况下,如果能够将从节点变成一个主节点,是不是就可以解决这个问题了呢?
答:是的,这个就是Sentinel哨兵的作用。
4.2哨兵的任务
Redis 的 Sentinel 系统用于管理多个 Redis 服务器(instance), 该系统执行以下三个任务:
监控(Monitoring): Sentinel 会不断地检查你的主服务器和从服务器是否运作正常。
提醒(Notification): 当被监控的某个 Redis 服务器出现问题时, Sentinel 可以通过 API 向管理员或者其他应用程序发送通知。
自动故障迁移(Automatic failover): 当一个主服务器不能正常工作时, Sentinel 会开始一次自动故障迁移操作, 它会进行选举,将其中一个从服务器升级为新的主服务器, 并让失效主服务器的其他从服务器改为复制新的主服务器; 当客户端试图连接失效的主服务器时, 集群也会向客户端返回新主服务器的地址, 使得集群可以使用新主服务器代替失效服务器。
4.2.1监控(Monitoring)
(1)Sentinel可以监控任意多个Master和该Master下的Slaves。(即多个主从模式)
(2)同一个哨兵下的、不同主从模型,彼此之间相互独立。
(3)Sentinel会不断检查Master和Slaves是否正常。

4.2.2自动故障切换(Automatic failover)
4.2.2.1Sentinel网络
监控同一个Master的Sentinel会自动连接,组成一个分布式的Sentinel网络,互相通信并交换彼此关于被监视服务器的信息。下图中,三个监控s1的Sentinel,自动组成Sentinel网络结构。

疑问:为什么要使用sentinel网络呢?
答:当只有一个sentinel的时候,如果这个sentinel挂掉了,那么就无法实现自动故障切换了。
在sentinel网络中,只要还有一个sentinel活着,就可以实现故障切换。
4.2.2.2故障切换的过程
(1)投票(半数原则)
当任何一个Sentinel发现被监控的Master下线时,会通知其它的Sentinel开会,投票确定该Master是否下线(半数以上,所以sentinel通常配奇数个)。
(2)选举
当Sentinel确定Master下线后,会在所有的Slaves中,选举一个新的节点,升级成Master节点。
其它Slaves节点,转为该节点的从节点。

(1)投票

(2)选举
(3)原Master重新上线
当原Master节点重新上线后,自动转为当前Master节点的从节点。

4.3哨兵模式部署
4.3.1需求
前提:已经存在一个正在运行的主从模式。
另外,配置三个Sentinel实例,监控同一个Master节点。
4.3.2配置Sentinel

S1哨兵配置如下:


S2哨兵配置如下:


S3哨兵配置如下:


(5)再打开三个xshell窗口,在每一个窗口中,启动一个哨兵实例,并观察日志输出

核心日志输出:

4.2.4测试
(1)先关闭6380节点。发现,确实重新指定了一个主节点

(2)再次上线6380节点。发现,6380节点成为了新的主节点的从节点。

4.3结论
Sentinel哨兵模式,确实能实现自动故障切换。提供稳定的服务。
4.4注意事项
如果哨兵和redis节点不在同一台服务器上,注意IP绑定的问题。
(1)主从模型,所有的节点,使用ip绑定

(2)所有的哨兵,也都使用ip去绑定主机

(3)所有的哨兵,都是通过主节点的ip,去监控主从模型
