Redis Sentinel(哨兵) 是 Redis 官方提供的高可用(HA)解決方案。由多個 Sentinel 進程組成集群,監控 Master/Slave 狀態,當 Master 客觀下線時,自動發起故障轉移,將最優 Slave 升級為新 Master,並通知客戶端更新拓撲。
/opt/redis/ ├── master-6380/ # redis.conf + data/ ├── slave-6381/ # redis.conf + data/ ├── slave-6382/ # redis.conf + data/ └── sentinel/ # sentinel.conf × 3 (不同端口 26379/26380/26381)
port 6380 pidfile /var/run/redis_6380.pid bind 0.0.0.0 daemonize yes logfile "master-6380.log" # 無需 slaveof,默認角色為 master
# 6381 port 6381 pidfile /var/run/redis_6381.pid slaveof 127.0.0.1 6380 # masterauth "yourpass" # 若 Master 有密碼 # 6382 同理,port/pidfile/slaveof 對應修改
redis-server master-6380/redis.conf redis-server slave-6381/redis.conf redis-server slave-6382/redis.conf redis-cli -p 6380 info replication # role:master, connected_slaves:2 ...
port 26379 pidfile /var/run/sentinel_26379.pid daemonize yes logfile "sentinel-26379.log" sentinel monitor mymaster 127.0.0.1 6380 2 # quorum=2,至少 2 個哨兵同意才判定客觀下線 sentinel down-after-milliseconds mymaster 5000 # 5s 無響應判主觀下線 sentinel failover-timeout mymaster 60000 # 故障轉移超時 60s sentinel parallel-syncs mymaster 1 # 轉移時並行同步的 Slave 數
其餘兩個 Sentinel 修改 port/pidfile/logfile 即可,sentinel monitor 保持一致。
redis-sentinel sentinel-26379.conf redis-sentinel sentinel-26380.conf redis-sentinel sentinel-26381.conf
kill -9 `cat /var/run/redis_6380.pid`+sdown master mymaster 127.0.0.1 6380 (主觀下線)+odown master mymaster 127.0.0.1 6380 #quorum 2/3 (客觀下線)+failover-triggered mymaster (發起故障轉移)+switch-master mymaster 127.0.0.1 6380 127.0.0.1 6382 (6382 升級為新 Master)redis-cli -p 6382 info replication → role:masterredis-cli -p 6381 info replication → master_host:127.0.0.1, master_port:6382new JedisSentinelPool("mymaster", sentinelSet, poolConfig)RedisClient.create(RedisURI.Builder.sentinel("host", 26379).withSentinelMasterId("mymaster").build())spring.redis.sentinel.master=mymaster; spring.redis.sentinel.nodes=host:26379,host:26380| 參數 | 建議值 | 說明 |
|---|---|---|
| down-after-milliseconds | 3000-5000 | 太小誤判,太大延遲故障發現 |
| quorum | (N/2)+1 | 3哨兵設2,5哨兵設3,平衡可用性與穩定性 |
| failover-timeout | 3-5 倍下線判定時間 | 防止頻繁發起轉移 |
| parallel-syncs | 1 | 避免同時同步過多 Slave 造成網絡擁塞 |
Redis Sentinel 以輕量級進程實現自動故障轉移,適合中小規模部署。生產環境務必:至少 3 個 Sentinel、跨機房部署、配置合理 quorum、啟用密碼認證、監控 Sentinel 自身存活。大規模場景建議升級 Redis Cluster(分片+副本)獲得水平擴展能力。