高可用Redis配置

Redis+keepalived高可用配置。虽然Redis支持主从,但由于从设备是只读状态,所以还涉及到主从状态的切换和同步。通过keepalived在状态切换时调用notify脚本,可以完成Redis的主从状态切换。

keepalive配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
! Configuration File for keepalived
vrrp_script chk_redis {
script "/root/keepalived/redis_check.sh"
interval 1
}
vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 61
priority 100
advert_int 1
nopreempt
unicast_src_ip 192.168.15.11
unicast_peer {
192.168.15.12
}
authentication {
auth_type admin
auth_pass admin
}
virtual_ipaddress {
192.168.15.13 dev eth0
}
track_script {
chk_redis
}
notify /root/keepalived/redis_alert.sh
}

其中,当这个vrrp的实例根据track_script的检测结果,状态发生变化时就会调用notify指定的脚本,完成相应的操作。notify调用脚本时会带上以下三个参数:

1
2
3
4
5
# arguments
# $1 = "GROUP"|"INSTANCE"
# $2 = name of group or instance
# $3 = target state of transition
# ("MASTER"|"BACKUP"|"FAULT")

redis_check.sh

检测redis的可用性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
REDIS_BIN='/usr/bin'
REDIS_LOCAL_HOST='127.0.0.1'
REDIS_LOCAL_PORT=6379
ALIVE=`$REDIS_BIN/redis-cli -h $REDIS_LOCAL_HOST -p $REDIS_LOCAL_PORT PING`
if [ "$ALIVE" == "PONG" ]; then
echo $ALIVE
exit 0
else
echo $ALIVE
exit 1
fi

redis_alert.sh

这个脚本的第三个参数,即$STATE是keepalived传递过来的目标状态。在这里,当keepalived由BACKUP变为MASTER时,将redis从设备断开主从连接(从设备升级为主设备),并保存当前状态到配置文件。相反,当keepalived由MASTER变为BACKUP时,将redis(上一个状态的主设备)配置为从设备。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
TYPE=$1
NAME=$2
STATE=$3
REDIS_BIN='/usr/bin'
REDIS_LOCAL_HOST='127.0.0.1'
REDIS_LOCAL_PORT=6379
REDIS_PEER='192.168.15.12'
REDIS_PEER_PORT='6379'
case $STATE in
MASTER)
$REDIS_BIN/redis-cli -h $REDIS_LOCAL_HOST -p $REDIS_LOCAL_PORT slaveof no one
$REDIS_BIN/redis-cli -h $REDIS_LOCAL_HOST -p $REDIS_LOCAL_PORT config rewrite
exit 0
;;
BACKUP)
$REDIS_BIN/redis-cli -h $REDIS_LOCAL_HOST -p $REDIS_LOCAL_PORT slaveof $REDIS_PEER $REDIS_PEER_PORT
$REDIS_BIN/redis-cli -h $REDIS_LOCAL_HOST -p $REDIS_LOCAL_PORT config rewrite
exit 0
;;
FAULT)
ps -ef | grep redis-server | grep -v grep | awk '{print $2}' | xargs kill
nohup /usr/bin/redis-server /etc/redis.conf &
exit 0
;;
*)
exit 1
;;
esac

SLAVE

配置和MASTER类似,需要注意的是redis_alert.sh中的REDIS_PEER需要指定对方。

如果您觉得这篇文章对您有帮助,不妨支持我一下!