前言

什么是哨兵

Redis Sentinel出生于2012年,Redis 2.4稳定后首次发布,它是一个旨在管理Redis集群的系统。

哨兵的任务

  1. 监控(Monitoring):Sentinel会不断地检查你的主服务器和从服务器是否运作正常
  2. 提醒(Notification):当被监控的某个Redis服务器出现问题时,Sentinel可以通过API向管理员或者其他应用程序发送通知
  3. 自动故障迁移(Automatic failover):当一个主服务器不能正常工作时,Sentinel 会开始一次自动故障迁移操作,它会将失效主
    服务器的其中一个从服务器升级为新的主服务器,并让失效主服务器的其他从服务器改为复制新的主服务器;当客户端试图连接失效的主
    服务器时,集群也会向客户端返回新主服务器的地址,使得集群可以使用新主服务器代替失效服务器

为什么要用到哨兵

1.从Redis宕机

这个相对而言比较简单,在Redis中从库重新启动后会自动加入到主从架构中,自动完成同步数据。在Redis2.8版本后,主从断线后恢复
的情况下实现增量复制。

2. 主Redis宕机

这个相对而言就会复杂一些,需要以下2步才能完成
i.第一步,在从数据库中执行SLAVEOF NO ONE命令,断开主从关系并且提升为主库继续服务
ii.第二步,将主库重新启动后,执行SLAVEOF命令,将其设置为其他库的从库,这时数据就能更新回来

搭建(一主二从三烧兵)

下载安装


集群配置

1. master.conf

port 8001
bind 127.0.0.1
#redis将以守护进程的方式运行,这样可以在redis服务启动的窗口中再可以进行其它操作
daemonize yes
pidfile "/var/run/redis_8001.pid"
#cluster-enabled  yes
#cluster-config-file  nodes_8001.conf
#cluster-node-timeout  15000
appendonly yes
#requirepass test123 设置redis客户端或者远程机器连接redis服务器需要的密码
#masterauth test123 从服务器和哨兵连接主服务器需要的密码
#cluster-require-full-coverage no
# Generated by CONFIG REWRITE
dir "/home/tengxing/Dtt/redis-cluster"

2. slave.conf(配置两个文件,不同的port)

port 8015
daemonize yes
slave-read-only yes 
#requirepass "yjxxclub"
slaveof 127.0.0.1 8001
#masterauth "yjxxclub"
bind 0.0.0.0
#cluster-require-full-coverage no
# Generated by CONFIG REWRITE
dir "/home/tengxing/Dtt/redis-cluster"

3. sentinel.conf(配置三个文件,不同的port)

port 8101
 daemonize yes
 protected-mode no
 logfile "/opt/redis-cluster/logs/sentinel_8101.log"
 #master-1
 sentinel monitor master-1 10.211.55.10 6381 1
 sentinel down-after-milliseconds master-1 5000
 sentinel failover-timeout master-1 18000
 sentinel auth-pass master-1 test123
 sentinel parallel-syncs master-1 1

最后如下图:

redis3.0.7集群部署 redis4.0集群搭建_redis3.0.7集群部署

启动服务

通过redis安装目录依次启动服务

sudo /usr/local/bin/redis-server  ~/Dtt/redis-sentinel/conf/redis_master_8001.conf
sudo /usr/local/bin/redis-server  ~/Dtt/redis-sentinel/conf/redis_slave_8005.conf
sudo /usr/local/bin/redis-server  ~/Dtt/redis-sentinel/conf/redis_slave_8006.conf
sudo /usr/local/bin/redis-sentinel ~/Dtt/redis-sentinel/conf/sentinel_8101.conf 
sudo /usr/local/bin/redis-sentinel ~/Dtt/redis-sentinel/conf/sentinel_8201.conf
sudo /usr/local/bin/redis-sentinel ~/Dtt/redis-sentinel/conf/sentinel_8301.conf

验证:

sudo /usr/local/bin/redis-cli -c -h 127.0.0.1 -p 8101 info sentinel

打出:

# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=master-1,status=ok,address=127.0.0.1:8001,slaves=2,sentinels=3

ok,搭建成功

后记

理解了原理以后配置非常的简单,其实并不复杂;搭建的同时只需要配置几个文件,然后启动即可,推荐编写一个脚本,避免多次操作,简单快捷。最后将我的配置放在github,便于参考。