Redis Sentinel
Redis Sentinel 用于监控主从实例、自动故障转移和提供主节点发现能力。它适合单主多从架构,不负责数据分片。
推荐架构
redis master 6379 redis replica 6379 redis replica 6379
| | |
+-----------+-----------+-----------+-----------+
| |
sentinel 26379 sentinel 26379
| |
sentinel 26379
生产环境至少部署 3 个 Sentinel,避免单点和误判。Sentinel 可以和 Redis 实例同机部署,也可以独立部署。
Redis 主从准备
先完成主从复制:
# replica 节点
replicaof 10.0.0.11 6379
masterauth change-me
requirepass change-me
确认主节点:
INFO replication
Sentinel 配置
创建 /data/redis/sentinel-26379/sentinel.conf:
port 26379
daemonize no
supervised systemd
logfile /data/redis/sentinel-26379/logs/sentinel.log
dir /data/redis/sentinel-26379/data
sentinel monitor mymaster 10.0.0.11 6379 2
sentinel auth-pass mymaster change-me
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
参数说明:
| 参数 | 说明 |
|---|---|
mymaster | 主节点逻辑名称,客户端会使用它发现主节点 |
2 | quorum,至少 2 个 Sentinel 判断主观下线后才推进故障转移 |
down-after-milliseconds | 多久无响应判定主观下线 |
failover-timeout | 故障转移超时时间 |
parallel-syncs | 故障转移后同时重新同步的从节点数量 |
systemd 服务
[Unit]
Description=Redis Sentinel 26379
After=network.target
[Service]
Type=notify
User=redis
Group=redis
ExecStart=/data/app/redis/current/bin/redis-sentinel /data/redis/sentinel-26379/sentinel.conf --supervised systemd
Restart=always
RestartSec=5
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target
启动:
systemctl daemon-reload
systemctl enable --now redis-sentinel-26379
systemctl status redis-sentinel-26379
Sentinel 命令
redis-cli -p 26379 sentinel masters
redis-cli -p 26379 sentinel master mymaster
redis-cli -p 26379 sentinel replicas mymaster
redis-cli -p 26379 sentinel sentinels mymaster
redis-cli -p 26379 sentinel get-master-addr-by-name mymaster
手动触发故障转移:
redis-cli -p 26379 sentinel failover mymaster
客户端连接
客户端应连接 Sentinel 地址列表,并通过 mymaster 动态发现当前主节点。不要把业务写死到某一个 Redis 主节点 IP。
客户端配置通常包含:
- Sentinel 地址列表。
- 主节点名称
mymaster。 - Redis 密码或 ACL 用户。
- 连接池和超时配置。
故障转移流程
- Sentinel 判定主节点主观下线。
- 多个 Sentinel 达成客观下线。
- Sentinel 选举出 Leader。
- Leader 从 replica 中选择新主节点。
- 新主节点执行
REPLICAOF NO ONE。 - 其他 replica 改为复制新主节点。
- 客户端通过 Sentinel 获取新主节点地址。
常见问题
| 现象 | 排查方向 |
|---|---|
| Sentinel 频繁切换 | 检查网络抖动、超时配置、节点负载 |
| 客户端仍写旧主 | 检查客户端是否支持 Sentinel,是否缓存旧地址 |
| 从节点未重新挂载 | 查看 Sentinel 日志和 Redis INFO replication |
| 无法认证 Redis | 检查 sentinel auth-pass、Redis requirepass 和 ACL |
Sentinel 配置文件会被自动重写,变更前建议先备份。