1. 程式人生 > >Redis叢集中主從自動切換之Sentinel(哨兵)

Redis叢集中主從自動切換之Sentinel(哨兵)

Redis Sentinel
Sentinel(哨兵)是用於監控redis叢集中Master狀態的工具,其已經被整合在redis2.4+的版本中

一、Sentinel作用:
1):Master狀態檢測 
2):如果Master異常,則會進行Master-Slave切換,將其中一個Slave作為Master,將之前的Master作為Slave
3):Master-Slave切換後,master_redis.conf、slave_redis.conf和sentinel.conf的內容都會發生改變,即master_redis.conf中會多一行slaveof的配置,sentinel.conf的監控目標會隨之調換
二、Sentinel工作方式:
1):每個Sentinel以每秒鐘一次的頻率向它所知的Master,Slave以及其他 Sentinel 例項傳送一個 PING 命令
2):如果一個例項(instance)距離最後一次有效回覆 PING 命令的時間超過 down-after-milliseconds 選項所指定的值, 則這個例項會被 Sentinel 標記為主觀下線。
3):如果一個Master被標記為主觀下線,則正在監視這個Master的所有 Sentinel 要以每秒一次的頻率確認Master的確進入了主觀下線狀態。
4):當有足夠數量的 Sentinel(大於等於配置檔案指定的值)在指定的時間範圍內確認Master的確進入了主觀下線狀態, 則Master會被標記為客觀下線
5):在一般情況下, 每個 Sentinel 會以每 10 秒一次的頻率向它已知的所有Master,Slave傳送 INFO 命令
6):當Master被 Sentinel 標記為客觀下線時,Sentinel 向下線的 Master 的所有 Slave 傳送 INFO 命令的頻率會從 10 秒一次改為每秒一次
7):若沒有足夠數量的 Sentinel 同意 Master 已經下線, Master 的客觀下線狀態就會被移除。 
若 Master 重新向 Sentinel 的 PING 命令返回有效回覆, Master 的主觀下線狀態就會被移除。

主觀下線和客觀下線
主觀下線

:Subjectively Down,簡稱 SDOWN,指的是當前 Sentinel 例項對某個redis伺服器做出的下線判斷。
客觀下線:Objectively Down, 簡稱 ODOWN,指的是多個 Sentinel 例項在對Master Server做出 SDOWN 判斷,並且通過 SENTINEL is-master-down-by-addr 命令互相交流之後,得出的Master Server下線判斷,然後開啟failover.

SDOWN適合於Master和Slave,只要一個 Sentinel 發現Master進入了ODOWN, 這個 Sentinel 就可能會被其他 Sentinel 推選出, 並對下線的主伺服器執行自動故障遷移操作。
ODOWN
只適用於Master,對於Slave的 Redis 例項,Sentinel 在將它們判斷為下線前不需要進行協商, 所以Slave的 Sentinel 永遠不會達到ODOWN.

三、配置:
1:指定監聽Master(三個節點)

# vi /main/redis/sentinel.conf
port 26379
daemonize yes
sentinel monitor mymaster 192.168.100.211 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 900000
sentinel auth-pass mymaster 15144
dir ./sentinel-16380

#上面配置檔案說明如下:

#第一行指定sentinel埠號
#第二行指定sentinel為後臺啟動
#第三行指定Sentinel去監視一個名為 mymaster 的Master,Master的IP地址為192.168.100.211,埠號為6379,最後的2表示當有2個Sentinel檢測到Master異常時才會判定其失效,即只有當2個Sentinel都判定Master失效了才會自動遷移,如果Sentinel的數量不達標,則不會執行自動故障遷移。
#第四行指定Sentinel判定Master斷線的時間。(單位為毫秒,判定為主觀下線SDOWN)
#第五行指定在執行故障轉移時,最多可以有多少個Slave同時對新的Master進行同步。這個數字設定為1,雖然完成故障轉移所需的時間會變長,但是可以保證每次只有1個Slave處於不能處理命令請求的狀態。
第六行若sentinel在該配置值內未能完成failover操作(即故障時master/slave自動切換),則認為本次failover失敗。
第七行當redis訪問都需要密碼的時候,即在redis.conf有配置requirepass項的時候,需要定義此項。

2:啟動sentinel(三個節點):
# /main/redis/src/redis-sentinel /main/redis/sentinel.conf

3:設定開機啟動(三個節點)
# echo "/main/redis/src/redis-sentinel /main/redis/sentinel.conf" >> /etc/rc.local

四、注意點:
1):首次啟動時,必須先啟動Master
2):Sentinel 只在 server 端做主從切換,app端要自己開發(例如Jedis庫的SentinelJedis,能夠監控Sentinel的狀態)
3):若Master已經被判定為下線,Sentinel已經選擇了新的Master,也已經將old Master改成Slave,但是還沒有將其改成new Master。若此時重啟old Master,則Redis叢集將處於無Master狀態,此時只能手動修改配置檔案,然後重新啟動叢集

到此redis叢集配置完畢