当主数据库挂了之后,需要手动设置新的主数据库,其他从数据库都需要重新设置新的主数据。手动切换的成本比较大,还会导致一段时间的服务不可用。这就需要讲上面的手动设置改成自动设置,也就是使用哨兵来配置。
哨兵Redis
的高可用解决方案,哨兵监控Redis
主服务器和绑定的从服务器,如果主服务器宕机了,自动将某个从服务器升级为新的服务器,然后发送通知给其他从服务器。
哨兵是一个独立的进程,和Redis一样,它也运行一个实例。主要有三个任务:
PING
命令,检查主从数据库运行是否正常,在设置down-after-milliseconds
毫秒,没有服务响应,就会标记主观下线,当其他哨兵也判断主观下线,判断主观下线的数量达到设置的值后,哨兵之间会进行投票,投票同意后,进行数据库升级。redis.conf
配置文件。replicaof
命令,和新数据库建立连接,并进行数据复制。在上面的主从模式的基础上添加哨兵,首先从解压文件夹复制sentinel.conf
到usr/local/redis
文件夹中:
cp sentinel.conf /usr/local/redis/
修改sentinel.conf
文件,需要修改的部分:
daemonize no
改成 daemonize yes
logfile ""
改成 logfile "redis_26379.log"
sentinel monitor <master-name> <ip> <redis-port> <quorum>
,设置成 sentinel monitor mymaster 127.0.0.1 6382 1
ip
主数据库IPredis-port
主数据库端口quorum
主从切换需要达到主动下线个数sentinel auth-pass mymaster 123456
,表示验证密码mymaster
哨兵的名称,需要唯一123456
数据库密码,所有主从数据库密码需要设置成一致。启动服务器:
[root@instance-3 redis]# bin/redis-sentinel sentinel.conf
查看logfile
启动日志:
看最后标记的三行,表明哨兵分别监控了主数据库
6380
、两个从数据库6381
、6382
。有上面的日志输出表明哨兵已经成功启动。
使用SHUTDOWN
命令关闭6380
主数据库服务:
[root@instance-3 redis]# bin/redis-cli -p 6380
127.0.0.1:6380> shutdown
(error) NOAUTH Authentication required.
127.0.0.1:6380> a
[root@instance-3 redis]# bin/redis-cli -p 6380
127.0.0.1:6380> auth xxx
OK
127.0.0.1:6380> SHUTDOWN
通过ps -ef |grep redis
查看6380
已经关闭:
[root@instance-3 redis]# ps -ef |grep redis
root 8822 1 0 Nov21 ? 00:00:58 /usr/local/redis/bin/redis-server *:6379
root 24707 1 0 10:35 ? 00:00:02 bin/redis-server *:6381
root 27500 1 0 10:47 ? 00:00:01 bin/redis-server *:6382
root 29247 1 0 10:54 ? 00:00:03 bin/redis-sentinel *:26379 [sentinel]
root 34131 17210 0 11:16 pts/1 00:00:00 grep --color=auto redis
查看哨兵日志logfile
:
表明主服务器从
6380
成功切换到了6382
,sentinel.conf
配置文件也修改了主从数据库配置。如果没有切换成功,日志报错-failover-abort-no-good-slave
,可能是没有设置验证密码sentinel auth-pass
。