一套完整可落地的 Sentinel 高可用部署方案,包括:
Redis 主从配置
Sentinel 配置
Spring Boot Java 配置
常见坑说明
验证步骤
假设:
A: 192.168.1.10 (Master)
B: 192.168.1.11 (Slave)
C: 192.168.1.12 (Slave)
Redis端口: 6379
Sentinel端口: 26379
密码: 1
master名称: mymaster
一、Redis 主从配置
① 配置 Master(A)
编辑 redis.conf:
vi redis.conf
修改以下内容:
bind 0.0.0.0
port 6379
daemonize yes
protected-mode no
requirepass 1
masterauth 1
⚠ 注意:
master 也建议写 masterauth,防止以后变成从节点
启动:
./redis-server redis.conf
验证:
./redis-cli -a 1
info replication
应该看到:
role:master
② 配置 Slave(B 和 C)
编辑 redis.conf:
bind 0.0.0.0
port 6379
daemonize yes
protected-mode no
requirepass 1
masterauth 1
replicaof 192.168.1.10 6379
启动:
./redis-server redis.conf
验证:
./redis-cli -a 1
info replication
应该看到:
role:slave
master_host:192.168.1.10
二、配置 Sentinel(关键)
建议:3台机器都启动 Sentinel(避免脑裂)
① 创建 sentinel.conf
每台机器新建:
vi sentinel.conf
内容如下:
port 26379
daemonize yes
protected-mode no
dir /tmp
sentinel monitor mymaster 192.168.1.10 6379 2
sentinel auth-pass mymaster 1
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1
参数解释
sentinel monitor mymaster 192.168.1.10 6379 2
意思:
监控 master 名字叫 mymaster
当前主节点是 192.168.1.10:6379
2 表示至少 2 个 sentinel 同意才算真正 down(避免误判)
② 启动 Sentinel
./redis-sentinel sentinel.conf
或者:
./redis-server sentinel.conf --sentinel
查看是否正常:
./redis-cli -p 26379
sentinel masters
三、测试自动切换
在 master 上写数据:
set test 123
关闭 A 上的 Redis:
pkill redis-server
观察 B 或 C:
info replication
应该会有一个变成:
role:master
说明自动切换成功 ✅
四、Spring Boot Java 配置
① application.yml 配置
spring:
redis:
password: 1
sentinel:
master: mymaster
nodes:
- 192.168.1.10:26379
- 192.168.1.11:26379
- 192.168.1.12:26379
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
② Maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
默认使用 Lettuce(推荐)。
五、Java 如何验证连接的是 Sentinel?
启动项目后,日志里会看到:
Connecting to Redis Sentinel
或者你可以打印当前 master:
@Autowired
private StringRedisTemplate redisTemplate;
@PostConstruct
public void test() {
redisTemplate.opsForValue().set("a","1");
}
当主切换后:
Java 不需要重启
自动连接新 master
六、生产环境重要注意点
1️⃣ 防火墙必须开放端口
开放:
6379
26379
否则 Sentinel 会失联。
2️⃣ 不要只开 1 个 Sentinel
必须 3 个以上。
否则:
容易误判
无法选举
3️⃣ Redis 密码坑点
必须:
requirepass 1
masterauth 1
sentinel auth-pass mymaster 1
spring.redis.password=1
少一个都会失败。
七、整体架构逻辑图(理解一下)
+------------------+
| Sentinel A |
+------------------+
|
+------------------+
| Sentinel B |
+------------------+
|
+------------------+
| Sentinel C |
+------------------+
↓ 监控
A (Master)
↑
B (Slave)
↑
C (Slave)
Java 只连接 Sentinel
Sentinel 告诉 Java 当前 Master 是谁
八、为什么银行系统必须用 Sentinel?
因为:
主机宕机自动切换
Java 无感知
不影响业务
满足高可用
九、再进阶一点
如果你未来系统 QPS 很高:
建议直接 Redis Cluster
不要再用 Sentinel
Sentinel 只解决:
✔ 主从高可用
❌ 不解决扩容