其他问题 - 虚拟IP切换

优质
小牛编辑
131浏览
2023-12-01

在sentinel进行切换时还会自动调用一个脚本(如果设置的话),做一些自动化操作,比如如果我们需要一个虚拟IP永远飘在Master上(这个VIP可不是被应用用来连接redis 的,用过的人都知道连接redis sentinel并不依赖于VIP的),那么可以在sentinel配置文件中配置:

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

在发生主从切换,Master发生变化时,该脚本会被sentinel进行调用,调用的参数如其配置文件所描述的:

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

因此,我们可以在failover.sh中进行判断,如果该脚本所运行的主机IP等于新的Master IP,那么将VIP加上,如果不等于,则该机器为Slave,就去掉VIP。通过这种方式进行VIP的切换:

  1. #!/bin/sh
  2. _DEBUG="on"
  3. DEBUGFILE=/tmp/sentinel_failover.log
  4. VIP='192.168.2.120'
  5. MASTERIP=${6}
  6. MASK='24'
  7. IFACE='eno33554960'
  8. MYIP=$(ip -4 -o addr show dev ${IFACE}| grep -v secondary| awk '{split($4,a,"/");print a[1]}')
  9. DEBUG () {
  10. if [ "$_DEBUG" = "on" ]; then
  11. echo `$@` >> ${DEBUGFILE}
  12. fi
  13. }
  14. set -e
  15. DEBUG date
  16. DEBUG echo $@
  17. DEBUG echo "Master: ${MASTERIP} My IP: ${MYIP}"
  18. if [ ${MASTERIP} = ${MYIP} ]; then
  19. if [ $(ip addr show ${IFACE} | grep ${VIP} | wc -l) = 0 ]; then
  20. /sbin/ip addr add ${VIP}/${MASK} dev ${IFACE}
  21. DEBUG date
  22. DEBUG echo "/sbin/ip addr add ${VIP}/${MASK} dev ${IFACE}"
  23. DEBUG date
  24. DEBUG echo "IP Arp cleaning: /usr/sbin/arping -q -f -c 1 -A ${VIP} -I ${IFACE}"
  25. /usr/sbin/arping -q -f -c 1 -A ${VIP} -I ${IFACE}
  26. DEBUG date
  27. DEBUG echo "IP Failover finished!"
  28. fi
  29. exit 0
  30. else
  31. if [ $(ip addr show ${IFACE} | grep ${VIP} | wc -l) != 0 ]; then
  32. /sbin/ip addr del ${VIP}/${MASK} dev ${IFACE}
  33. DEBUG echo "/sbin/ip addr del ${VIP}/${MASK} dev ${IFACE}"
  34. fi
  35. exit 0
  36. fi
  37. exit 1

最早这样的用法是一个日本人写的blog,请参见:http://blog.youyo.info/blog/2014/05/24/redis-cluster/