redis哨兵配置主從


redis哨兵的啟動和redis實例的啟動沒有關系。所以可以在任何機器上啟動redis哨兵。至少要保證有兩個哨兵在運行,要不然宕機后哨兵會找不到主節點。

配置步驟:

1.在redis的配置文件中添加鑒權和驗證(添加requirepass和masterauth),redis主從都需要配置,配置的密碼一般相同。

2.redis一般都在內網運行,所以注釋掉#bind 127.0.0.1

3.關閉保護模式,protected-mode 把yes改為no

4.添加sentinel.conf配置文件:

#sentinel端口
port 26379
#工作路徑,注意路徑不要和主重復
dir "/usr/local/redis-6379"
# 守護進程模式
daemonize yes
#關閉保護模式
protected-mode no
# 指明日志文件名
logfile "./sentinel.log"
#哨兵監控的master,主從配置一樣,這里只用輸入redis主節點的ip/port和法定人數。
sentinel monitor mymaster 192.168.125.128 6379 1
# master或slave多長時間(默認30秒)不能使用后標記為s_down狀態。
sentinel down-after-milliseconds mymaster 5000
#若sentinel在該配置值內未能完成failover操作(即故障時master/slave自動切換),則認為本次failover失敗。
sentinel failover-timeout mymaster 18000
#設置master和slaves驗證密碼
sentinel auth-pass mymaster 123456 
sentinel parallel-syncs mymaster 1//指定了在執行故障轉移時, 最多可以有多少個從服務器同時對新的主服務器進行同步

Sentinel參數在運行時可以使用SENTINEL SET命令更改

上面配置中的mymaster為該主從的名字,代碼中會使用。

通過哨兵查看集群的信息:

$ redis-cli -p 26379
sentinel master mymaster//查看master的狀態 
SENTINEL slaves mymaster //查看salves的狀態
SENTINEL sentinels mymaster //查看哨兵的狀態
SENTINEL get-master-addr-by-name mymaster//獲取當前master的地址
info sentinel//查看哨兵信息

啟動哨兵:

方式一:redis-sentinel /path/to/sentinel.conf(推薦,這種方式啟動和redis實例沒有任何關系)
方式二:redis-server /path/to/sentinel.conf --sentinel

java測試代碼:

public static void main(String[] args) {
        Set<String> sentinels = new HashSet<String>();
        sentinels.add(new HostAndPort("192.168.125.128", 26379).toString());
        sentinels.add(new HostAndPort("192.168.125.129", 26379).toString());
        sentinels.add(new HostAndPort("192.168.125.130", 26379).toString());
        JedisSentinelPool sentinelPool = new JedisSentinelPool("mymaster", sentinels);
        System.out.println("Current master: " + sentinelPool.getCurrentHostMaster().toString());
        Jedis master = sentinelPool.getResource();
        master.auth("pwdisadmin");
        master.set("username","cczz");
        Jedis master2 = sentinelPool.getResource();
        master2.auth("pwdisadmin");
        String value = master2.get("username");
        System.out.println("username: " + value);
        master2.close();
        sentinelPool.close();
        sentinelPool.destroy();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM