主从复制与 Sentinel
约 576 字大约 2 分钟
布欧-Lewyon
2026-05-15
主从复制
配置
# slave.conf
replicaof 127.0.0.1 6379 # 指向 Master
replica-read-only yes # 只读(默认)# 运行时设置
SLAVEOF 127.0.0.1 6379 # 旧版命令(兼容)
REPLICAOF 127.0.0.1 6379 # 新版(Redis 5+)
# 查看复制状态
INFO replication
# 断开复制(升级为 Master)
SLAVEOF NO ONE同步过程
- Slave 向 Master 发送
PSYNC。 - Master 执行
BGSAVE生成 RDB 发送给 Slave。 - Slave 加载 RDB,之后接收增量命令。
- 后续持续从
repl_backlog增量同步。
# 配置复制缓冲区大小
repl-backlog-size 256mb # 缓冲区大小(防主从断开后全量重新同步)
repl-backlog-ttl 3600Sentinel
Sentinel 是 Redis 的高可用方案,自动监控和故障转移。
配置
# sentinel.conf
port 26379
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 30000
sentinel parallel-syncs mymaster 1| 配置 | 含义 |
|---|---|
monitor mymaster 127.0.0.1 6379 2 | 监控名为 mymaster 的主节点,2 个 Sentinel 同意才认定故障 |
down-after-milliseconds 5000 | 5 秒无响应判定为下线 |
failover-timeout 30000 | 故障转移超时 30 秒 |
parallel-syncs 1 | 故障切换后,同时从新 Master 同步的 Slave 数 |
# 启动 Sentinel
redis-sentinel sentinel.conf
# 查看 Sentinel 信息
redis-cli -p 26379 SENTINEL masters
redis-cli -p 26379 SENTINEL replicas mymaster
# 手动故障转移
redis-cli -p 26379 SENTINEL FAILOVER mymaster客户端连接 Sentinel
// Java 客户端通过 Sentinel 获取 Master 地址
Set<String> sentinels = new HashSet<>(Arrays.asList(
"192.168.1.1:26379", "192.168.1.2:26379", "192.168.1.3:26379"
));
JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels);
try (Jedis jedis = pool.getResource()) {
jedis.set("key", "value");
}小结
- 主从复制:Master 读写,Slave 只读,
SLAVEOF/REPLICAOF配置。 - 全量同步传 RDB,增量同步传 backlog。
- Sentinel:3 个哨兵 + Master + 2 个 Slave 组成高可用架构。
- 故障转移自动选新 Master,应用无感知。
- 客户端通过
JedisSentinelPool连接 Sentinel 获取 Master。
上一节:事务与 Lua 脚本 下一节:Redis Cluster
