spring boot本身不处理redis故障转移,真正起作用的是redis sentinel集群与lettuce客户端的配合;lettuce原生支持动态拓扑发现和自动重连,能监听+switch-master事件,在主节点宕机后自动连接新主,无需修改代码或重启服务。

Spring Boot 本身不处理 Redis 故障转移,真正起作用的是 Redis Sentinel(哨兵)集群和客户端驱动(Lettuce)的配合。只要配置正确,应用在主节点宕机后能自动连上新主,无需改代码、重启服务。
spring-boot-starter-data-redis 默认用 Lettuce,不是 Jedis
Spring Boot 2.x 起默认使用 Lettuce 作为 Redis 客户端,它原生支持 Sentinel 拓扑动态发现和自动重连;Jedis 需要额外封装或手动处理连接切换,容易卡死或抛 RedisConnectionFailureException。
- 确认依赖里没显式引入
jedis,否则可能覆盖默认行为 - 如果必须用 Jedis,得自己写
RedisConnectionFactory并注入哨兵地址,但不推荐——Lettuce 更稳 -
Lettuce的RedisSentinelConfiguration会在初始化时主动向所有哨兵节点询问当前 master 地址,并持续监听+switch-master事件
application.yml 中 sentinel 配置必须写对字段名和格式
常见错误是把 nodes 写成字符串逗号分隔(像旧版 Jedis 风格),或漏掉 master 名称,导致启动时报 Cannot connect to sentinel 或直接 fallback 到单节点模式。
Redis 缓存和数据结构管理技能。通过自然语言操作 Redis,支持 String、Hash、List、Set、ZSet、Stream 等数据结构操作。当用户提到 Redis、缓存、消息队列、会话存储时使用此技能。
-
spring.redis.sentinel.master值必须和哨兵配置里sentinel monitor <name> ...</name>的<name></name>完全一致(区分大小写),例如mymaster -
spring.redis.sentinel.nodes必须是 YAML list 格式,不能写成"127.0.0.1:26379,127.0.0.1:26389"—— 正确写法是:sentinel: master: mymaster nodes: - 127.0.0.1:26379 - 127.0.0.1:26389 - 127.0.0.1:26399 - 如果 Redis 主从启用了密码,必须配
spring.redis.password(不是sentinel.auth-pass),Lettuce 会自动将该密码用于 master/slave 连接
哨兵节点 bind 地址不能是 127.0.0.1
Windows 下本地部署时,若哨兵 sentinel.conf 里写 bind 127.0.0.1,Spring Boot 应用会连不上哨兵——因为 Lettuce 从哨兵拿到 master 地址后,会尝试用该地址(如 127.0.0.1:6379)去连,而哨兵返回的地址是它自己视角里的,未必等于应用视角。
- 哨兵配置中应设为局域网 IP(如
bind 192.168.1.100)或注释掉bind行(让其监听所有接口) - 同时确保
protected-mode no,否则哨兵拒绝外部连接 - 验证方式:用
redis-cli -h 192.168.1.100 -p 26379 info sentinel能查到sentinel_masters:1且master-link-status:ok
真正关键的不是配置多复杂,而是哨兵之间能否互相通信、能否正确识别主从状态、以及 Lettuce 是否拿到了有效的 master 地址。故障转移是否生效,看日志里有没有 Switching master 和后续的 Connecting to new master —— 这些才是自动切换发生的证据,而不是“配完就一定行”。










