Redis 主從配置中,主節點掛了以后,需要手動把一個從節點升成主節點,把另外的從節點做為新的主節點的從節點。redis 提供了 sentinel,可以自動的進行上面的處理。
在 redis 的安裝包里,有一個 sentinel 的示例。運行下面的命令,可以獲得一個去掉空行和注釋后的配置文件:
cat sentinel.conf | grep -v "#" | grep -v "^$" > sentinel-26379.conf
編輯上面生成的文件,編輯后的內容如下:
port 26379 daemonize yes pidfile /var/run/redis-sentinel.pid logfile "s26379.log" dir /opt/data/redis sentinel monitor mymaster 127.0.0.1 6379 2 sentinel down-after-milliseconds mymaster 30000 sentinel parallel-syncs mymaster 1 sentinel failover-timeout mymaster 180000 sentinel deny-scripts-reconfig yes
其中 mymaster 是自定義的名稱,如果取另外的名稱,需要把所有出現的地方都要改掉。
sentinel monitor mymaster 127.0.0.1 6379 2 配置的是主節點的 IP 和 端口
運行下面的命令,啟動 sentinel
redis-sentinel sentinel-26379.conf
啟動成功后,我們查看 sentinel-26379.conf 這個配置文件,可以看到文件發生了變化,自動加入了從節點的信息
port 26379 daemonize yes pidfile "/var/run/redis-sentinel-26379.pid" logfile "s26379.log" dir "/opt/data/redis" sentinel myid 53d9f86064361bcd0b02901f7cc4f12b6230a6f7 sentinel deny-scripts-reconfig yes sentinel monitor mymaster 127.0.0.1 6379 2 sentinel config-epoch mymaster 0 sentinel leader-epoch mymaster 0 # Generated by CONFIG REWRITE protected-mode no sentinel known-replica mymaster 127.0.0.1 6380 sentinel known-replica mymaster 127.0.0.1 6381 sentinel current-epoch 0
配置完成后,使用 jedis 去連 redis 時,發現報 connection refuse 的錯誤。最后發現 JedisSentinelPool 返回的主節點的 IP 是 127.0.0.1 ,而不是 redis 主節點真正的 IP。 所以上面的 sentinel 的配置文件中的 redis 的主節點的IP 需要改成真正的 IP。