Redis 虛擬IP切換

2018-08-03 11:50 更新

在sentinel進行切換時還會自動調用一個腳本(如果設置的話),做一些自動化操作,比如如果我們需要一個虛擬IP永遠飄在Master上(這個VIP可不是被應用用來連接redis 的,用過的人都知道連接redis sentinel并不依賴于VIP的),那么可以在sentinel配置文件中配置:

sentinel client-reconfig-script mymaster /redis/script/failover.sh

在發(fā)生主從切換,Master發(fā)生變化時,該腳本會被sentinel進行調用,調用的參數如其配置文件所描述的:

# The following arguments are passed to the script:
#
# <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
#
# <state> is currently always "failover"
# <role> is either "leader" or "observer"
# 
# The arguments from-ip, from-port, to-ip, to-port are used to communicate
# the old address of the master and the new address of the elected slave
# (now a master).

因此,我們可以在failover.sh中進行判斷,如果該腳本所運行的主機IP等于新的Master IP,那么將VIP加上,如果不等于,則該機器為Slave,就去掉VIP。通過這種方式進行VIP的切換:

#!/bin/sh
_DEBUG="on"
DEBUGFILE=/tmp/sentinel_failover.log
VIP='192.168.2.120'
MASTERIP=${6}
MASK='24'
IFACE='eno33554960'
MYIP=$(ip -4 -o addr show dev ${IFACE}| grep -v secondary| awk '{split($4,a,"/");print a[1]}')

DEBUG () {
        if [ "$_DEBUG" = "on" ]; then
                echo `$@` >>  ${DEBUGFILE}
        fi
}

set -e
DEBUG date 
DEBUG echo $@  
DEBUG echo "Master: ${MASTERIP} My IP: ${MYIP}"
if [ ${MASTERIP} = ${MYIP} ]; then
        if [ $(ip addr show ${IFACE} | grep ${VIP} | wc -l) = 0 ]; then
                /sbin/ip addr add ${VIP}/${MASK} dev ${IFACE}
        DEBUG date
                DEBUG echo "/sbin/ip addr add ${VIP}/${MASK} dev ${IFACE}"
        DEBUG date
        DEBUG echo "IP Arp cleaning: /usr/sbin/arping -q -f -c 1 -A ${VIP} -I ${IFACE}" 
                /usr/sbin/arping -q -f -c 1 -A ${VIP} -I ${IFACE}
        DEBUG date 
        DEBUG echo "IP Failover finished!"
        fi
        exit 0
else
        if [ $(ip addr show ${IFACE} | grep ${VIP} | wc -l) != 0 ]; then
                /sbin/ip addr del ${VIP}/${MASK} dev ${IFACE}
                DEBUG echo "/sbin/ip addr del ${VIP}/${MASK} dev ${IFACE}"
        fi
        exit 0
fi
exit 1

最早這樣的用法是一個日本人寫的blog,請參見:http://blog.youyo.info/blog/2014/05/24/redis-cluster/



以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號