Redis主從+KeepAlived實現高可用

來源:互聯網
上載者:User

Redis主從+KeepAlived實現高可用

Redis是我們當下比較流行使用的非關聯式資料庫,可支援多樣化的資料類型,多線程高並發支援,redis運行在記憶體擁有更快的讀寫。因為redis的表現如此出色,如何能保障redis在運行中能夠應對宕機故障,

所以今天總結了下redis主從高可用的搭建,參考了網上一些大神的部落格文章,發現很多都是有坑的,所以本人在此分享一次,希望能協助到大家。

Redis特點
Redis 是完全開源免費的,遵守BSD協議,是一個高效能的key-value資料庫。

Redis 與其他 key - value 緩衝產品有以下三個特點:

Redis支援資料的持久化,可以將記憶體中的資料保持在磁碟中,重啟的時候可以再次載入進行使用。

Redis不僅僅支援簡單的key-value類型的資料,同時還提供如:字串(String), 雜湊(Map), 列表(list), 集合(sets) 和有序集合(sorted sets)等資料結構的儲存。

Redis支援資料的備份,即master-slave模式的資料備份。

Redis 優勢
效能極高 – Redis能讀的速度是100K+次/s,寫的速度是80K+次/s 。

豐富的資料類型 – Redis支援二進位案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 資料類型操作。

原子 – Redis的所有操作都是原子性的,同時Redis還支援對幾個操作全並後的原子性執行。

豐富的特性 – Redis還支援 publish/subscribe, 通知, key 到期等等特性。

準備環境
CentOS7 --> 172.16.81.140 -->主Redis -->主Keepalived

CentOS7 --> 172.16.81.141 -->從Redis -->備Keepalived

VIP --> 172.16.81.139

redis(一般3.0版本以上都行)

KeepAlived(直接線上安裝的)

Redis編譯安裝

1、提前準備好的redis軟體放在/opt目錄下:redis-4.0.6.tar.gz

cd /opt
tar -zxvf redis-4.0.6.tar.gz
mv redis-4.0.6 redis
cd redis
makeMALLOC=libc
make PREFIX=/usr/local/redis install

2、配置redis啟動指令碼

vim /etc/init.d/redis

#!/bin/sh

#chkconfig:2345 80 90
# Simple Redisinit.d script conceived to work on Linux systems
# as it doeSUSE of the /proc filesystem.

#配置redis連接埠號碼
REDISPORT=6379
#配置redis啟動命令路徑
EXE=/usr/local/redis/bin/redis-server
#配置redis串連命令路徑
CLIEXE=/usr/local/redis/bin/redis-cli
#配置redis運行PID路徑
PIDFILE=/var/run/redis_6379.pid
#配置redis的設定檔路徑
CONF="/etc/redis/redis.conf"
#配置redis的串連認證密碼
REDISPASSWORD=123456

function start () {
        if [ -f $PIDFILE ]

        then

                echo "$PIDFILE exists,process is already running or crashed"

        else

                echo "Starting Redisserver..."

                $EXE $CONF &

        fi
}

function stop () {
        if [ ! -f $PIDFILE ]

        then

                echo "$PIDFILE does not exist, process is not running"

        else

                PID=$(cat $PIDFILE)

                echo "Stopping ..."

                $CLIEXE -p $REDISPORT -a $REDISPASSWORD shutdown

                while [ -x /proc/${PID} ]

                do

                    echo "Waiting forRedis to shutdown ..."

                    sleep 1

                done

                echo "Redis stopped"

        fi
}

function restart () {
        stop
       
        sleep 3
       
        start
}

case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    restart
    ;;
    *)
    echo -e "\e[31m Please use $0 [start|stop|restart] asfirst argument \e[0m"
    ;;
esac

授予執行許可權:

chmod +x /etc/init.d/redis

添加開機啟動:

chkconfig --add redis

chkconfig redis on

查看:chkconfig --list | grep redis

此次實驗事先關閉了防火牆和selinux,生產環境建議開啟防火牆。

3、添加redis命令環境變數

#vi /etc/profile
#添加下一行參數
exportPATH="$PATH:/usr/local/redis/bin"
#環境變數生效
source /etc/profile
4、啟動redis服務

service redis start
#檢查啟動情況

ps -ef | grep redis

註:在我們兩台伺服器上先執行同樣的操作安裝完成redis,接下來安裝完成後,就直接進入配置主從環境。

Redis主從配置

引申回到前面的設計模式,我們的思路是以140作為主,141作為從,139作為VIP飄逸地址,應用通過139的6379連接埠訪問redis資料庫。

正常運行下,當主節點140宕機後,VIP飄逸到141上,這時141就會接管140成為主節點,140就會成為從節點,繼續提供讀寫操作。

 當140恢複正常後,這時140會與141進行一次資料同步,140原有的資料不會丟失,還會同步宕機之間已經寫入到141的資料,資料同步完成之後,

VIP會因為權重的原因重新回到140節點上並成為主節點,141會因為失去VIP會重新成為從節點,恢複到初始狀態繼續提供不間斷的讀寫服務。

1、配置redis的設定檔

Master-140設定檔

vim /etc/redis/redis.conf
    bind 0.0.0.0
    port 6379
    daemonize yes
    requirepass 123456
    slave-serve-stale-data yes
    slave-read-only no

Slave-141設定檔

vim /etc/redis/redis.conf
    bind 0.0.0.0
    port 6379
    daemonize yes
    slaveof 172.16.81.140 6379
    masterauth 123456
    slave-serve-stale-data yes
    slave-read-only no

2、配置完成後重啟redis服務!驗證主從是否正常。

主節點140終端登入測試:

[root@localhost ~]# redis-cli -a 123456
127.0.0.1:6379> INFO
.
.
.
# Replication
role:master
connected_slaves:1
slave0:ip=172.16.81.141,port=6379,state=online,offset=105768,lag=1
master_replid:f83fcc3c98614d770f2205831fef1e877fa3f482
master_replid2:1f25604997a4ad3eb8344e8155990e78acd93312
master_repl_offset:105768
second_repl_offset:447
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:447
repl_backlog_histlen:105322

從節點141終端登入測試:

[root@localhost ~]# redis-cli -a 123456
127.0.0.1:6379> info
.
.
.
# Replication
role:slave
master_host:172.16.81.140
master_port:6379
master_link_status:up
master_last_io_seconds_ago:5
master_sync_in_progress:0
slave_repl_offset:105992
slave_priority:100
slave_read_only:0
connected_slaves:0
master_replid:f83fcc3c98614d770f2205831fef1e877fa3f482
master_replid2:1f25604997a4ad3eb8344e8155990e78acd93312
master_repl_offset:105992
second_repl_offset:447
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:239
repl_backlog_histlen:105754
3、同步測試

主節點140

從節點141

到此redis的主從已經完成!

KeepAlived配置實現雙機熱備

使用Keepalived實現VIP,並且通過notify_master、notify_backup、notify_fault、notify_stop來實現容災。

1、配置Keepalived設定檔

主Keepalived設定檔

vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
  notification_email {
    acassen@firewall.loc
    failover@firewall.loc
    sysadmin@firewall.loc
  }
  notification_email_from Alexandre.Cassen@firewall.loc
  smtp_server 192.168.200.1
  smtp_connect_timeout 30
  router_id redis01
}

vrrp_script chk_redis {
    script "/etc/keepalived/script/redis_check.sh"
    interval 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eno16777984
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    track_script {
        chk_redis
    }
    virtual_ipaddress {
        172.16.81.139
    }
   
    notify_master /etc/keepalived/script/redis_master.sh
    notify_backup /etc/keepalived/script/redis_backup.sh
    notify_fault  /etc/keepalived/script/redis_fault.sh 
    notify_stop  /etc/keepalived/script/redis_stop.sh
}

備用Keepalived設定檔

vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
  notification_email {
    acassen@firewall.loc
    failover@firewall.loc
    sysadmin@firewall.loc
  }
  notification_email_from Alexandre.Cassen@firewall.loc
  smtp_server 192.168.200.1
  smtp_connect_timeout 30
  router_id redis02
}

vrrp_script chk_redis {
    script "/etc/keepalived/script/redis_check.sh"
    interval 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eno16777984
    virtual_router_id 51
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    track_script {
        chk_redis
    }
    virtual_ipaddress {
        172.16.81.139
    }
   
    notify_master /etc/keepalived/script/redis_master.sh
    notify_backup /etc/keepalived/script/redis_backup.sh
    notify_fault  /etc/keepalived/script/redis_fault.sh 
    notify_stop  /etc/keepalived/script/redis_stop.sh
}

2、配置指令碼

Master KeepAlived -- 140

建立存放指令碼目錄:mkdir -p /etc/keepalived/script/

cd /etc/keepalived/script/

[root@localhost script]# cat redis_check.sh
#!/bin/bash

ALIVE=`/usr/local/redis/bin/redis-cli -a 123456 PING`

if [ "$ALIVE" == "PONG" ];then

echo $ALIVE

exit 0

else

echo $ALIVE

exit 1

fi


[root@localhost script]# cat redis_master.sh
#!/bin/bash
REDISCLI="/usr/local/redis/bin/redis-cli -a 123456"
LOGFILE="/var/log/keepalived-redis-state.log"

sleep 15

echo "[master]" >> $LOGFILE

date >> $LOGFILE

echo "Being master...." >>$LOGFILE 2>&1


echo "Run SLAVEOF cmd ...">> $LOGFILE

$REDISCLI SLAVEOF 172.16.81.141 6379 >>$LOGFILE  2>&1
if [ $? -ne 0 ];then
    echo "data rsync fail." >>$LOGFILE 2>&1
else
    echo "data rsync OK." >> $LOGFILE  2>&1
fi

sleep 10 #延遲10秒以後待資料同步完成後再取消同步狀態

echo "Run SLAVEOF NO ONE cmd ...">> $LOGFILE

$REDISCLI SLAVEOF NO ONE >> $LOGFILE 2>&1
if [ $? -ne 0 ];then
    echo "Run SLAVEOF NO ONE cmd fail." >>$LOGFILE 2>&1
else
    echo "Run SLAVEOF NO ONE cmd OK." >> $LOGFILE  2>&1
fi

[root@localhost script]# cat redis_backup.sh
#!/bin/bash

REDISCLI="/usr/local/redis/bin/redis-cli -a 123456"

LOGFILE="/var/log/keepalived-redis-state.log"

echo "[backup]" >> $LOGFILE

date >> $LOGFILE

echo "Being slave...." >>$LOGFILE 2>&1

sleep 15 #延遲15秒待資料被對方同步完成之後再切換主從角色

echo "Run SLAVEOF cmd ...">> $LOGFILE

$REDISCLI SLAVEOF 172.16.81.141 6379 >>$LOGFILE  2>&1

[root@localhost script]# cat redis_fault.sh
#!/bin/bash

LOGFILE=/var/log/keepalived-redis-state.log

echo "[fault]" >> $LOGFILE

date >> $LOGFILE

[root@localhost script]# cat redis_stop.sh
#!/bin/bash

LOGFILE=/var/log/keepalived-redis-state.log

echo "[stop]" >> $LOGFILE

date >> $LOGFILE

Slave KeepAlived -- 141
建立存放指令碼目錄:mkdir -p /etc/keepalived/script/

cd /etc/keepalived/script/

[root@localhost script]# cat redis_check.sh
#!/bin/bash

ALIVE=`/usr/local/redis/bin/redis-cli -a 123456 PING`

if [ "$ALIVE" == "PONG" ]; then

echo $ALIVE

exit 0

else

echo $ALIVE

exit 1

fi


[root@localhost script]# cat redis_master.sh
#!/bin/bash

REDISCLI="/usr/local/redis/bin/redis-cli -a 123456"

LOGFILE="/var/log/keepalived-redis-state.log"

 

echo "[master]" >> $LOGFILE

date >> $LOGFILE

echo "Being master...." >>$LOGFILE 2>&1

 

echo "Run SLAVEOF cmd ...">> $LOGFILE

$REDISCLI SLAVEOF 172.16.81.140 6379 >>$LOGFILE  2>&1

sleep 10 #延遲10秒以後待資料同步完成後再取消同步狀態

 

echo "Run SLAVEOF NO ONE cmd ...">> $LOGFILE

$REDISCLI SLAVEOF NO ONE >> $LOGFILE 2>&1

[root@localhost script]# cat redis_backup.sh
#!/bin/bash

REDISCLI="/usr/local/redis/bin/redis-cli -a 123456"

LOGFILE="/var/log/keepalived-redis-state.log"
 

echo "[backup]" >> $LOGFILE

date >> $LOGFILE

echo "Being slave...." >>$LOGFILE 2>&1

 
sleep 15 #延遲15秒待資料被對方同步完成之後再切換主從角色

echo "Run SLAVEOF cmd ...">> $LOGFILE

$REDISCLI SLAVEOF 172.16.81.140 6379 >>$LOGFILE  2>&1

[root@localhost script]# cat redis_fault.sh
#!/bin/bash

LOGFILE=/var/log/keepalived-redis-state.log

echo "[fault]" >> $LOGFILE

date >> $LOGFILE

[root@localhost script]# cat redis_stop.sh
#!/bin/bash

LOGFILE=/var/log/keepalived-redis-state.log

echo "[stop]" >> $LOGFILE

date >> $LOGFILE
3、啟動服務

systemctl start keepalived

systemctl enable keepalived

4、測試服務是否正常

ps -ef | grep keepalived

ping 172.16.81.139

查看VIP地址

測試連接redis是否正常

redis-cli -h 172.16.81.139 -p 6379 -a 123456

Keepalived測試完成!!

測試容錯移轉情況
關閉主redis服務,查看從redis是否會接管VIP變成主?然後再新的主redis141上插入資料,測試當140恢複,資料是否存在?141的是否會變成從節點?

1、主140關閉redis

service redis stop

2、查看141狀態

測試VIP串連遠端連線

 通過INFO可以查看狀態資訊

可以看到從節點的141已經變成master節點了。

3、插入資料

4、開啟140主節點

service redis start

5、查看140和141的主從狀態

141的狀態,變回了從

140的狀態,變回了主

我們在140上查看剛剛在141上插入的新資料

資料存在,證明主從切換是正常的!!!

上面是本人親測過的,如有問題請留言!!!

本文永久更新連結地址:https://www.bkjia.com/Linux/2018-03/151377.htm

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.