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