Redis Sentinel 配置文件深度解析与最佳实践
2025-07-05 01:12:31作者:蔡怀权
Sentinel 基础概念
Redis Sentinel 是 Redis 官方提供的高可用性解决方案,用于管理 Redis 主从架构并自动处理故障转移。sentinel.conf 文件是 Sentinel 的核心配置文件,它定义了 Sentinel 实例的行为方式和监控规则。
核心配置详解
1. 基本运行参数
protected-mode no
port 26379
daemonize no
pidfile /var/run/redis-sentinel.pid
protected-mode
:建议在生产环境中设置为yes
,只允许本地连接,避免安全风险port
:Sentinel 默认监听 26379 端口daemonize
:是否以守护进程方式运行,生产环境建议设为yes
pidfile
:进程 ID 文件位置,便于服务管理
2. 日志配置
loglevel notice
logfile ""
loglevel
:日志级别,生产环境建议notice
,调试时可设为debug
logfile
:空字符串表示输出到标准输出,生产环境应指定日志文件路径
3. 监控主节点配置
sentinel monitor mymaster 127.0.0.1 6379 2
这是 Sentinel 最核心的配置项,格式为:
sentinel monitor <master-name> <ip> <port> <quorum>
mymaster
:主节点名称,可自定义127.0.0.1 6379
:主节点地址和端口2
:仲裁数,表示至少需要 2 个 Sentinel 同意才能判定主节点客观下线
4. 认证配置
sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
sentinel auth-user mymaster sentinel-user
- Redis 6.0+ 支持 ACL,可以配置用户名和密码
- 如果使用旧版 Redis,只需配置
auth-pass
- 所有 Sentinel 和 Redis 节点应使用相同的认证信息
高级配置选项
1. 故障检测与转移
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
down-after-milliseconds
:判定节点不可达的超时时间(毫秒)parallel-syncs
:故障转移时允许同时同步的从节点数量failover-timeout
:故障转移超时时间,影响多种故障转移行为
2. 脚本通知
sentinel notification-script mymaster /var/redis/notify.sh
sentinel client-reconfig-script mymaster /var/redis/reconfig.sh
notification-script
:事件通知脚本,用于告警client-reconfig-script
:客户端重配置脚本,故障转移后通知应用- 脚本需要有可执行权限,且执行时间不能超过 60 秒
3. 安全配置
sentinel deny-scripts-reconfig yes
requirepass yourpassword
deny-scripts-reconfig
:禁止运行时修改脚本配置,增强安全性requirepass
:设置 Sentinel 自身的访问密码
生产环境最佳实践
- 部署至少 3 个 Sentinel 实例:确保高可用性,避免脑裂问题
- 合理设置仲裁数:通常设为 Sentinel 数量的一半加一
- 启用认证:保护 Sentinel 和 Redis 节点的通信安全
- 配置日志轮转:避免日志文件过大影响系统运行
- 设置适当的超时参数:根据网络环境调整
down-after-milliseconds
- 测试故障转移:定期模拟故障,验证 Sentinel 的自动恢复能力
常见问题解决方案
- 网络分区问题:适当增加
down-after-milliseconds
值,避免误判 - 脑裂问题:确保仲裁数设置合理 (N/2 + 1)
- 脚本执行失败:检查脚本权限和执行时间限制(60秒)
- ACL 配置问题:Redis 6.0+ 需要正确配置 Sentinel 用户的权限
通过合理配置 sentinel.conf 文件,可以构建一个健壮的 Redis 高可用架构,确保业务系统在面对节点故障时能够自动恢复,保障服务的连续性。