概述
在部署redis 的時候,如果redis宕機,緩存將不可用,redis提供了哨兵模式保證redis實現高可用。
即一台主機兩台從機,三台哨兵主機,如果主實例宕機,哨兵將將一台從機升級為主機。實現高可用。
配置方法
1.IP地址配置如下
主 127.0.0.1 6001
從 127.0.0.1 6002
從 127.0.0.1 6003
哨兵
127.0.0.1 16001
127.0.0.1 16002
127.0.0.1 16002
2.修改配置
將 redis.con 拷貝兩份 redis1.conf redis2.conf
修改配置如下:
編輯 redis.conf
bind 192.168.1.88 127.0.0.1
protected-mode no
daemonize yes
port 6001
pidfile "/var/run/redis_6001.pid"
編輯 redis1.conf
bind 192.168.1.88 127.0.0.1
protected-mode no
daemonize yes
port 6002
pidfile "/var/run/redis_6002.pid"
slaveof 127.0.0.1 6001
編輯 redis2.conf
bind 192.168.1.88 127.0.0.1
protected-mode no
port 6003
daemonize yes
pidfile "/var/run/redis_6003.pid"
slaveof 127.0.0.1 6001
編輯 哨兵文件
將哨兵文件拷貝兩份
sentinel.conf sentinel1.conf sentinel2.conf
編輯 sentinel.conf
port 16001
daemonize yes
sentinel monitor mymaster 127.0.0.1 6001 2
編輯 sentinel1.conf
port 16002
daemonize yes
sentinel monitor mymaster 127.0.0.1 6001 2
編輯 sentinel2.conf
port 16003
daemonize yes
sentinel monitor mymaster 127.0.0.1 6001 2
配置完成
注意
這里如果需要使用哨兵模式連接的話,注意不能使用 127.0.0.1 需要使用對外的IP地址。
3.啟動 redis
./bin/redis-server etc/redis.conf
./bin/redis-server etc/redis1.conf
./bin/redis-server etc/redis2.conf
啟動哨兵
./bin/redis-sentinel ./etc/sentinel.conf
./bin/redis-sentinel ./etc/sentinel1.conf
./bin/redis-sentinel ./etc/sentinel2.conf
驗證
新開一個命令行窗口進入redis的src目錄,用redis-cli工具登錄其中一個哨兵
./bin/redis-cli -p 16001
連接成功后運行如下命令
sentinel master mymaster
我們可以看到主機端口為 6001
我們手工關閉 6001的實例。
可以看到 6001 斷開了。
可以看到6002 變為主機了。可以看到 6002 的配置文件 slaveof 127.0.0.1 6001 沒有了。
測試設置數據:
連接到 6002
./bin/redis-cli -p 6002
set name redis
連接到6001
get name
可以獲取到數據 redis
我們連接到6003 ,設置數據,我們可以從機是不能設置數據的。
sentinel 作用
A、Master 狀態監測
B、如果Master 異常,則會進行Master-slave 轉換,將其中一個Slave作為Master,將之前的Master作為Slave
C、Master-Slave切換后,redis.conf、redis1.conf和redis2.conf,sentinel.conf 的內容都會發生改變,sentinel.conf的監控目標會隨之調換
sentinel monitor mymaster 127.0.0.1 6002 2