keepalived实现redis主从高可用

方案说明

两台机器(称为A和B),以统一的VIP对外提供服务

1.正常情况下,A和B都启动,B会把A的数据同步过来(BisslaveofA)

2.当A挂了后,VIP漂移到B;B的keepalived通知redis执行:slaveofnoone,由B提供服务

3.当A起来后,VIP不切换,仍在B上面;而A的keepalived通知redis执行slaveofB,开始把B的数据同步过来(AisslaveofB)

4.依此循环

也就是说:

当两台机器都正常时,一个为master,一个为slave;

当master挂掉时,slave升级为master;

当原master再次起来时,它不会抢占,而是作为slave;依此循环

机器

10.75.201.67:/home/redis

10.75.201.66:/home/redis

初次启动时,10.75.201.67为master,10.75.201.66为slave

配置

//A机器
vrrp_script chk_nutcraker {
                script "/home/redis/redis/bin/redis_check.sh"
                interval 2
}
vrrp_instance VI_2 {
        state BACKUP        #both BACKUP
        interface eth1
        virtual_router_id 12
        priority 101    #101 on master, 100 on backup
        nopreempt       #both nopreempt
        track_script {
                chk_nutcraker
        }
        virtual_ipaddress {
             10.75.201.3
        }
        notify /home/redis/redis/bin/redis_notify.sh
}
//B机器
vrrp_script chk_nutcraker {
                script "/home/redis/redis/bin/redis_check.sh"
                interval 2
}
vrrp_instance VI_2 {
        state BACKUP        #both BACKUP
        interface eth1
        virtual_router_id 12
        priority 100    #101 on master, 100 on backup
        nopreempt       #both nopreempt
        track_script {
                chk_nutcraker
        }
        virtual_ipaddress {
             10.75.201.3
        }
        notify /home/redis/redis/bin/redis_notify.sh
}

检测redis是否正常的脚本:

[root@redhat1~]#cat/home/redis/redis/bin/redis_check.sh

#!/bin/bash

ALIVE=`/home/redis/redis/bin/redis-cli PING`
if [ "$ALIVE" == "PONG" ]; then
  echo $ALIVE
  exit 0
else
  echo $ALIVE
  exit 1
fi

redis根据keepalived状态转移而更新自己的状态:进入master时slaveofnoone,进入backup时,slaveof另一台机器:

[root@redhat1~]#cat/home/redis/redis/bin/redis_notify.sh

#!/bin/bash

REMOTE=10.75.201.67  #在10.75.201.67机器上则为10.75.201.66
PORT=6379

REDIS_HOME=/home/redis/redis
REDISCLI="$REDIS_HOME/bin/redis-cli"
LOGFILE="$REDIS_HOME/logs/redis_notify.log"

DATE_TIME=`date "+%Y-%m-%d %H:%M:%S"`

TYPE=$1
NAME=$2
STATE=$3

case $STATE in
        "MASTER") 
                  echo "$DATE_TIME:became master:" >> $LOGFILE
                  $REDISCLI SLAVEOF NO ONE >> $LOGFILE 2>&1 
                  exit 0
                  ;;
        "BACKUP")  
                  echo "$DATE_TIME:became slave:" >> $LOGFILE
                  $REDISCLI SLAVEOF $REMOTE $PORT >> $LOGFILE  2>&1
                  exit 0
                  ;;
        "FAULT")  
                  echo "$DATE_TIME:[fault]" >> $LOGFILE
                  exit 0
                  ;;
        *)        echo "unknown state"
                  exit 1
                  ;;
Esac

相关推荐