Sentinel 哨兵是 redis 官方提供的高可用方案,可以用它來監(jiān)控多個 Redis 服務(wù)實例的運(yùn)行情況。Redis Sentinel 是一個運(yùn)行在特殊模式下的 Redis 服務(wù)器。Redis Sentinel 是在多個Sentinel 進(jìn)程環(huán)境下互相協(xié)作工作的。
Sentinel 系統(tǒng)有三個主要任務(wù):
● 監(jiān)控:Sentinel 不斷的檢查主服務(wù)和從服務(wù)器是否按照預(yù)期正常工作。
● 提醒:被監(jiān)控的 Redis 出現(xiàn)問題時,Sentinel 會通知管理員或其他應(yīng)用程序。
● 自動故障轉(zhuǎn)移:監(jiān)控的主 Redis 不能正常工作,Sentinel 會開始進(jìn)行故障遷移操作。將一個從服務(wù)器升級新的主服務(wù)器。 讓其他從服務(wù)器掛到新的主服務(wù)器。同時向客戶端提供新的主服務(wù)器地址。
Sentinel 配置文件
復(fù)制三份sentinel.conf文
三個文件分別命名:
● sentinel26380.conf
● sentinel26382.conf
● sentinel26384.conf
● 執(zhí)行復(fù)制命令 cp sentinel.conf xxx.conf
● 修改 port 26380、 port 26382、 port 26384
● 修改 sentinel monitor mymaster 127.0.0.1 6380 2
格式:sentinel monitor <name> <masterIP> <masterPort> <Quorum 投票數(shù)>
Sentinel監(jiān)控主(Master)Redis, Sentinel根據(jù)Master的配置自動發(fā)現(xiàn)Master的Slave,Sentinel默認(rèn)端口號為26379 。
sentinel26380.conf
(1) 修改 port
(2)修改監(jiān)控的 master 地址
sentinel26382.conf 修改port 26382 , master的port 6382
sentinel26384.conf 修改port 26384 , master的port 6382
啟動 Reids
查看 Master 的配置信息
連接到 6382 端口
使用 info 命令查看 Master/Slave
redis安裝時make編譯后就產(chǎn)生了redis-sentinel程序文件,可以在一個redis中運(yùn)行多個sentinel進(jìn)程。
啟動一個運(yùn)行在Sentinel模式下的Redis服務(wù)實例
./redis-sentinel sentinel 配置文件
執(zhí)行以下三條命令,將創(chuàng)建三個監(jiān)視主服務(wù)器的Sentinel實例:
./redis-sentinel ../sentinel26380.conf
./redis-sentinel ../sentinel26382.conf
./redis-sentinel ../sentinel26384.conf
在 XShell 開啟三個窗口分別執(zhí)行:
讓 Master 的 Redis 停止服務(wù), 執(zhí)行 shutdown
先執(zhí)行 info replication 確認(rèn) Master 的 Redis ,再執(zhí)行 shutdown
查看當(dāng)前 Redis 的進(jìn)程情況
在 Master 執(zhí)行 shutdown 后, 稍微等一會 Sentinel 要進(jìn)行投票計算,從可用的 Slave選舉新的 Master。
查看 Sentinel 日志,三個 Sentinel 窗口的日志是一樣的。
查看新的 Master
查看原 Slave 的變化
重新啟動 6382
查看 6384 的信息
測試數(shù)據(jù):在 Master 寫入數(shù)據(jù)
在 6382 上讀取數(shù)據(jù),不能寫入
● Sentinel 會不斷檢查 Master 和 Slave 是否正常
● 如果 Sentinel 掛了,就無法監(jiān)控,所以需要多個哨兵,組成 Sentinel 網(wǎng)絡(luò),一個健康的Sentinel 至少有 3 個 Sentinel 應(yīng)用。 彼此在獨立的物理機(jī)器或虛擬機(jī)。
● 監(jiān)控同一個 Master 的 Sentinel 會自動連接,組成一個分布式的 Sentinel 網(wǎng)絡(luò),互相通信并交換彼此關(guān)于被監(jiān)控服務(wù)器的信息
● 當(dāng)一個 Sentinel 認(rèn)為被監(jiān)控的服務(wù)器已經(jīng)下線時,它會向網(wǎng)絡(luò)中的其它 Sentinel 進(jìn)行確認(rèn),判斷該服務(wù)器是否真的已經(jīng)下線
● 如果下線的服務(wù)器為主服務(wù)器,那么 Sentinel 網(wǎng)絡(luò)將對下線主服務(wù)器進(jìn)行自動故障轉(zhuǎn)移, 通過將下線主服務(wù)器的某個從服務(wù)器提升為新的主服務(wù)器,并讓其從服務(wù)器轉(zhuǎn)移到新的主服務(wù)器下,以此來讓系統(tǒng)重新回到正常狀態(tài)
● 下線的舊主服務(wù)器重新上線,Sentinel 會讓它成為從,掛到新的主服務(wù)器下
主從復(fù)制,解決了讀請求的分擔(dān),從節(jié)點下線,會使得讀請求能力有所下降,Master 下線,寫請求無法執(zhí)行
Sentinel 會在 Master 下線后自動執(zhí)行故障轉(zhuǎn)移操作,提升一臺 Slave 為 Master,并讓其它Slave 成為新 Master 的 Slave。