主从复制解决了"数据有副本",但master 宕机后谁来把某台 replica 提升为新 master?人工操作需要分钟级,业务不可接受。**Sentinel(哨兵)**是 Redis 官方的高可用组件:监控、通知、自动故障转移。本章解析 Sentinel 的架构、判定机制与 Raft 选举,以及 7.x 场景的部署实践。
Sentinel 四大职责:
| 职责 | 说明 |
|---|---|
| 监控(Monitoring) | 周期性 PING 所有 master/replica/sentinel |
| 通知(Notification) | 实例异常时通知管理员/应用 |
| 自动故障转移(Automatic failover) | master 下线时选举 replica 提升为新 master |
| 配置提供(Configuration provider) | 客户端通过 Sentinel 发现当前 master 地址 |
单个 Sentinel 在 down-after-milliseconds 内未收到 PING 回复,标记该实例 sdown(subjective down)——只是"我认为它挂了"。
Sentinel 通过 SENTINEL is-master-down-by-addr 询问其他 Sentinel 对 master 的看法,达到 quorum 数量的确认后标记 odown(objective down),触发故障转移流程。
触发故障转移前,Sentinel 集群先选举一个领导者负责执行(与 Raft 的 Leader Election 类似):
SENTINEL is-master-down-by-addr 请求毛遂自荐;每个 Sentinel 在每个 epoch(纪元)中只有一票;Leader 按以下优先级选择 replica(依次比较,先分胜负即停):
slave_repl_offset);# 查看 replica 状态
> sentinel replicas mymaster
1) 1) "name"
2) "127.0.0.1:6380"
3) "slave-repl-offset"
4) "123456"REPLICAOF NO ONE,使其成为新 master;REPLICAOF <new_master> 重新指向;replid2 支持 PSYNC2 部分同步);sentinel monitor mymaster 127.0.0.1 6379 2
sentinel auth-pass mymaster <password>
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1| 配置 | 含义 |
|---|---|
monitor | 监控的 master 名/地址/端口/quorum(判定 odown 所需确认数) |
down-after-milliseconds | 主观下线判定超时 |
parallel-syncs | 故障转移后同时向新 master 全量同步的 replica 数(1 最稳) |
failover-timeout | 故障转移总超时 |
__sentinel__:hello 频道发布/订阅消息相互发现,replica 列表则从 master 的 INFO replication 获取;配置变更通过 pub/sub 通道同步。// Jedis Sentinel 客户端:自动发现 master,故障转移后自动切换
Set<String> sentinels = new HashSet<>(Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380", "127.0.0.1:26381"));
JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels);
try (Jedis jedis = pool.getResource()) {
jedis.set("k", "v"); // 透明地读写当前 master
}# redis-cli 直接问 Sentinel
> sentinel get-master-addr-by-name mymaster
1) "127.0.0.1"
2) "6379"| 维度 | Sentinel | Redis Cluster |
|---|---|---|
| 分片 | ❌ 单写点 | ✅ 16384 slot 分片 |
| 故障转移 | Sentinel 自动 | 集群节点自动(Gossip) |
| 数据扩展 | 只读扩展 | 读写均可扩展 |
| 复杂度 | 低(3 进程 + 主从) | 高(多节点 + 槽位管理) |
| 适用 | 中小规模、单写多读 | 大规模、需分片 |
选型建议:数据量单机可承载、需要高可用 → Sentinel;数据量超出单机、需要横向扩展 → Cluster(下一章详解)。
parallel-syncs 过大:多 replica 同时全量同步,可能压垮新 master。下一章讲解过期策略:Redis 如何删除过期键(惰性 + 定期),以及内存淘汰 LRU/LFU。