天天看點

3台伺服器Redis高可用哨兵模式

3台伺服器Redis高可用哨兵模式

學習

redis

高可用

    • 3.1 主redis配置
    • 3.2 從redis配置
    • 1. 介紹
    • 2. redis程式安裝
    • 3. 哨兵模式配置
    • 3.3 啟動redis和哨兵
    • 4. 總結

3台伺服器Redis高可用哨兵模式

Redis 的 Sentinel 系統用于管理多個 Redis 伺服器(instance), 該系統執行以下三個任務: 

監控(Monitoring): Sentinel 會不斷地檢查你的主伺服器和從伺服器是否運作正常。 

提醒(Notification): 當被監控的某個 Redis 伺服器出現問題時, Sentinel 可以通過 API 向管理者或者其他應用程式發送通知。 

自動故障遷移(Automatic failover): 當一個主伺服器不能正常工作時, Sentinel 會開始一次自動故障遷移操作, 它會将失效主伺服器的其中一個從伺服器更新為新的主伺服器, 并讓失效主伺服器的其他從伺服器改為複制新的主伺服器; 當用戶端試圖連接配接失效的主伺服器時, 叢集也會向用戶端傳回新主伺服器的位址, 使得叢集可以使用新主伺服器代替失效伺服器。 

Redis Sentinel 是一個分布式系統, 你可以在一個架構中運作多個 Sentinel 程序(progress), 這些程序使用流言協定(gossip protocols)來接收關于主伺服器是否下線的資訊, 并使用投票協定(agreement protocols)來決定是否執行自動故障遷移, 以及選擇哪個從伺服器作為新的主伺服器。 

雖然 Redis Sentinel 釋出為一個單獨的可執行檔案 redis-sentinel , 但實際上它隻是一個運作在特殊模式下的 Redis 伺服器, 你可以在啟動一個普通 Redis 伺服器時通過給定 –sentinel 選項來啟動 Redis Sentinel 。

環境 

CentOS7.2 

redis3.2.8

伺服器IP redis端口 哨兵端口 伺服器角色
10.1.0.160 6379 26379
10.1.0.161 從1
10.1.0.71 從2

以下是單redis安裝腳本,可适用于單redis使用。 

cat install_redis.sh

#!/usr/bin/env bash
# It's Used to be install redis.
# Created on 2016/10/19 11:18.
# @author: Chinge_Yang.
# Version: 1.0

function install_redis () {
#################################################################################################
        sourcepackage_dir="/tmp"
        redis_install_dir="/usr/local/redis"
        cd ${sourcepackage_dir}
        if [ ! -f " redis-stable.tar.gz" ]; then
                wget http://download.redis.io/releases/redis-stable.tar.gz
        fi
        cd ${makework_dir}
        tar -zxvf ${sourcepackage_dir}/redis-stable.tar.gz
        cd redis-stable
        make PREFIX=/usr/local/redis install
        return_echo "make"
        mkdir -p /usr/local/redis/{etc,var}
        rsync -avz redis.conf  /usr/local/redis/etc/
        sed -i 's@pidfile.*@pidfile /var/run/redis-server.pid@' $redis_install_dir/etc/redis.conf
        sed -i "s@logfile.*@logfile $redis_install_dir/var/redis.log@" $redis_install_dir/etc/redis.conf
        sed -i "s@^dir.*@dir $redis_install_dir/var@" $redis_install_dir/etc/redis.conf
        sed -i 's/daemonize no/daemonize yes/g' /usr/local/redis/etc/redis.conf
        sed -i 's/^# bind 127.0.0.1/bind 127.0.0.1/g' /usr/local/redis/etc/redis.conf
        rsync -avz ${sourcepackage_dir}/init.d/redis-server /etc/init.d/
        /etc/init.d/redis-server start
        chkconfig --add redis-server
        chkconfig redis-server on
#################################################################################################
}

install_redis
           

redis啟停腳本示例: 

cat redis-server

#!/bin/bash 
#
# redis - this script starts and stops the redis-server daemon
#
# chkconfig:   - 85 15 
# description:  Redis is a persistent key-value database
# processname: redis-server
# config:      /usr/local/redis/etc/redis.conf 
# config:      /etc/sysconfig/redis
# pidfile:     /usr/local/redis/var/redis-server.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

redis="/usr/local/redis/bin/redis-server"
prog=$(basename $redis)

REDIS_CONF_FILE="/usr/local/redis/etc/redis.conf"

[ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis

lockfile=/var/lock/subsys/redis-server

start() {
    [ -x $redis ] || exit 5
    [ -f $REDIS_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $redis $REDIS_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog 
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $prog: "
    killproc $redis -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
           

redis-sentinel啟停腳本示例:

#!/bin/bash 
#
# redis-sentinel - this script starts and stops the redis-server sentinel daemon
#
# chkconfig:   - 85 15 
# description:  Redis sentinel 
# processname: redis-server
# config:      /usr/local/redis/etc/sentinel.conf 
# config:      /etc/sysconfig/redis
# pidfile:     /usr/local/redis/var/redis-sentinel.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

redis="/usr/local/redis/bin/redis-sentinel"
prog=$(basename $redis)

REDIS_CONF_FILE="/usr/local/redis/etc/sentinel.conf"

[ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis

lockfile=/var/lock/subsys/redis-sentinel

start() {
    [ -x $redis ] || exit 5
    [ -f $REDIS_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $redis $REDIS_CONF_FILE --sentinel
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog 
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $prog: "
    killproc $redis -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
           

3台主機相同設定:

  1. 按照前面單redis安裝方法安裝程式;
  2. 建立相應資料目錄;
mkdir -p /usr/local/redis/data/redis
mkdir -p /usr/local/redis/data/sentinel
mkdir -p /usr/local/redis/sbin
vim /usr/local/redis/sbin/redis-server  # 使用上文中的示例腳本
vim /usr/local/redis/sbin/redis-sentinel  # 使用上文中的示例腳本
           

vim redis.conf

daemonize yes
pidfile "/usr/local/redis/var/redis-server.pid"
port 6379
tcp-backlog 128
timeout 0
tcp-keepalive 0
loglevel notice
logfile "/usr/local/redis/var/redis-server.log"
databases 16
save 900 1    
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb 
dir "/usr/local/redis/data/redis"
masterauth "20170310"
requirepass "20170310"
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
           

群集檔案配置 

vim sentinel.conf

port 26379
pidfile "/usr/local/redis/var/redis-sentinel.pid"
dir "/usr/local/redis/data/sentinel"
daemonize yes
logfile "/usr/local/redis/var/redis-sentinel.log"
sentinel monitor mymaster 10.1.0.160 6379 2
sentinel parallel-syncs mymaster 2
sentinel auth-pass mymaster 20170310
           

相對主redis配置,多添加了如下行:

slaveof 10.1.0.160 6379
           

vim redis.conf

daemonize yes
pidfile "/usr/local/redis/var/redis-server.pid"
port 6379
tcp-backlog 128
timeout 0
tcp-keepalive 0
loglevel notice
logfile "/usr/local/redis/var/redis-server.log"
databases 16
save 900 1    
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb 
dir "/usr/local/redis/data/redis"
masterauth "20170310"
requirepass "20170310"
slaveof 10.1.0.160 6379  
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 90
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
           

vim sentinel.conf

port 26379
pidfile "/usr/local/redis/var/redis-sentinel.pid"
dir "/usr/local/redis/data/sentinel"
daemonize yes
logfile "/usr/local/redis/var/redis-sentinel.log"
sentinel monitor mymaster 10.1.0.160 6379 2
sentinel config-epoch mymaster 0
           

啟動redis,主從都要啟動 

/usr/local/redis/sbin/redis-server start

啟動群集監控,主從都要啟動 

/usr/local/redis/sbin/redis-sentinel start

啟動報錯處理

錯誤1:
WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.

解決方法(overcommit_memory)
1. `vim /etc/sysctl.conf`添加如下設定 , 然後`sysctl -p`
"vm.overcommit_memory = 1"
可選值:0、1、2。

0, 表示核心将檢查是否有足夠的可用記憶體供應用程序使用;如果有足夠的可用記憶體,記憶體申請允許;否則,記憶體申請失敗,并把錯誤傳回給應用程序。
1, 表示核心允許配置設定所有的實體記憶體,而不管目前的記憶體狀态如何。
2, 表示核心允許配置設定超過所有實體記憶體和交換空間總和的記憶體

注意:redis在dump資料的時候,會fork出一個子程序,理論上child程序所占用的記憶體和parent是一樣的,比如parent占用 的記憶體為8G,這個時候也要同樣配置設定8G的記憶體給child,如果記憶體無法負擔,往往會造成redis伺服器的down機或者IO負載過高,效率下降。所 以這裡比較優化的記憶體配置設定政策應該設定為 1(表示核心允許配置設定所有的實體記憶體,而不管目前的記憶體狀态如何)。
這裡又涉及到Overcommit和OOM。

什麼是Overcommit和OOM?
在Unix中,當一個使用者程序使用malloc()函數申請記憶體時,假如傳回值是NULL,則這個程序知道目前沒有可用記憶體空間,就會做相應的處理工作。許多程序會列印錯誤資訊并退出。
Linux使用另外一種處理方式,它對大部分申請記憶體的請求都回複"yes",以便能跑更多更大的程式。因為申請記憶體後,并不會馬上使用記憶體。這種技術叫做Overcommit。
當記憶體不足時,會發生OOM killer(OOM=out-of-memory)。它會選擇殺死一些程序(使用者态程序,不是核心線程),以便釋放記憶體。

Overcommit的政策
Linux下overcommit有三種政策(Documentation/vm/overcommit-accounting):
0. 啟發式政策。合理的overcommit會被接受,不合理的overcommit會被拒絕。
1. 任何overcommit都會被接受。
2. 當系統配置設定的記憶體超過swap+N%*實體RAM(N%由vm.overcommit_ratio決定)時,會拒絕commit。
overcommit的政策通過vm.overcommit_memory設定。
overcommit的百分比由vm.overcommit_ratio設定。

# echo 2 > /proc/sys/vm/overcommit_memory
# echo 80 > /proc/sys/vm/overcommit_ratio

當oom-killer發生時,linux會選擇殺死哪些程序
選擇程序的函數是oom_badness函數(在mm/oom_kill.c中),該函數會計算每個程序的點數(0~1000)。
點數越高,這個程序越有可能被殺死。
每個程序的點數跟oom_score_adj有關,而且oom_score_adj可以被設定(-1000最低,1000最高)。

錯誤2:
WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.

echo 511 > /proc/sys/net/core/somaxconn

錯誤3:
16433:X 12 Jun 14:52:37.734 * Increased maximum number of open files to 10032 (it was originally set to 1024).

新裝的linux預設隻有1024,當負載較大時,會經常出現error: too many open files

ulimit -a:使用可以檢視目前系統的所有限制值

vim /etc/security/limits.conf
在檔案的末尾加上

* soft nofile 65535
* hard nofile 65535

執行su或者重新關閉連接配接使用者再執行ulimit -a就可以檢視修改後的結果。 
           

故障切換機制

  1. 啟動群集之後,群集程式預設會在主從的sentinel.conf檔案中加入群集資訊

主:

port 26379
pidfile "/usr/local/redis/var/redis-sentinel.pid"
dir "/usr/local/redis/data/sentinel"
daemonize yes
logfile "/usr/local/redis/var/redis-sentinel.log"
sentinel myid aeff525d03a2234ef834808f7991761db03a1973
sentinel monitor mymaster 10.1.0.160 6379 2
sentinel parallel-syncs mymaster 2
sentinel auth-pass mymaster 20170310
# Generated by CONFIG REWRITE
sentinel config-epoch mymaster 0
sentinel leader-epoch mymaster 0
sentinel known-slave mymaster 10.1.0.71 6379
sentinel known-slave mymaster 10.1.0.161 6379
sentinel current-epoch 0
           

從1:

port 26379
pidfile "/usr/local/redis/var/redis-sentinel.pid"
dir "/usr/local/redis/data/sentinel"
daemonize yes
logfile "/usr/local/redis/var/redis-sentinel.log"
sentinel myid 01b1b7674abe648f6a2344fc5610e73b7e87cb8a
sentinel monitor mymaster 10.1.0.160 6379 2
sentinel config-epoch mymaster 0
# Generated by CONFIG REWRITE
sentinel leader-epoch mymaster 0
sentinel current-epoch 0
           

從2:

port 26379
pidfile "/usr/local/redis/var/redis-sentinel.pid"
dir "/usr/local/redis/data/sentinel"
daemonize yes
logfile "/usr/local/redis/var/redis-sentinel.log"
sentinel myid f1589f48079b3b3b536add4e2e01a36304aeba8c
sentinel monitor mymaster 10.1.0.160 6379 2
sentinel config-epoch mymaster 0
# Generated by CONFIG REWRITE
sentinel leader-epoch mymaster 0
sentinel current-epoch 0
           

模拟主故障

[root@show160 redis]# /usr/local/redis/bin/redis-cli -p 6379
127.0.0.1:6379> AUTH 20170310
OK
127.0.0.1:6379> DEBUG SEGFAULT
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected> quit
           

從哨兵配置檔案中可以看到目前的主庫的已經發生了改變

繼續閱讀