Sentinel 指南

sentinel.conf 配置

建议至少 3 个 Sentinel 实例以支持基于仲裁的故障转移。

# sentinel.conf
port 26379
daemonize yes
logfile /var/log/redis/sentinel.log
dir /tmp

# monitor: name host port quorum
sentinel monitor mymaster 127.0.0.1 6379 2

# Timeout before considering master down (milliseconds)
sentinel down-after-milliseconds mymaster 5000

# How many replicas can be simultaneously reconfigured during failover
sentinel parallel-syncs mymaster 1

# Failover timeout (ms): how long before re-trying failed failover
sentinel failover-timeout mymaster 60000

# Authentication (if master requires a password)
sentinel auth-pass mymaster s3cret

# TLS (Redis 6+)
# sentinel tls-port 26380
# sentinel tls-cert-file /path/to/cert.pem

# Start Sentinel
# redis-sentinel /etc/redis/sentinel.conf
# or: redis-server /etc/redis/sentinel.conf --sentinel

Sentinel API 命令

# Connect to Sentinel (port 26379 by default)
redis-cli -p 26379

# Check master info
SENTINEL master mymaster

# List all monitored masters
SENTINEL masters

# List replicas of a master
SENTINEL replicas mymaster

# List other Sentinel instances
SENTINEL sentinels mymaster

# Get current master address (useful for clients)
SENTINEL get-master-addr-by-name mymaster
# Returns: 1) "127.0.0.1"  2) "6379"

# Check Sentinel health
SENTINEL ping

# Reset state of monitored master
SENTINEL reset mymaster

# Trigger a manual failover
SENTINEL failover mymaster

# Flush config to disk
SENTINEL flushconfig

通过 Sentinel 连接(Node.js)

// ioredis Sentinel connection
const Redis = require("ioredis");
const client = new Redis({
  sentinels: [
    { host: "sentinel1", port: 26379 },
    { host: "sentinel2", port: 26379 },
    { host: "sentinel3", port: 26379 }
  ],
  name: "mymaster",
  password: "s3cret",        // master password
  sentinelPassword: "sentpass", // sentinel auth (Redis 6+)
  role: "master"             // "master" or "slave"
});

// ioredis auto-discovers new master on failover
client.on("error", err => console.error("Redis error:", err));
client.on("+switch-master", (master, oldHost, oldPort, newHost, newPort) => {
  console.log(`Failover: ${newHost}:${newPort}`);
});

故障转移流程

步骤描述
1. 主观下线(SDOWN)某 Sentinel 在 down-after-milliseconds 内无法联系主节点
2. 客观下线(ODOWN)达到仲裁数量的 Sentinel 一致认为主节点宕机
3. 领导者选举Sentinel 选出一个领导者来管理故障转移
4. 副本提升选择最优副本并提升为主节点
5. 重新配置其他副本和客户端重新配置为使用新主节点

监控与事件

# Subscribe to Sentinel events
redis-cli -p 26379 PSUBSCRIBE '*'

# Common event channels:
# +sdown         - instance entered subjective down
# -sdown         - instance left subjective down
# +odown         - instance entered objective down
# -odown         - instance left objective down
# +slave         - new replica discovered
# +sentinel      - new sentinel discovered
# +failover-state-reconf-slaves - failover started
# +failover-end  - failover completed
# +switch-master - master address changed

# Monitor Sentinel logs
tail -f /var/log/redis/sentinel.log