当前位置: 首页 > news >正文

Redis哨兵模式在Spring Boot项目中的使用与实践

Redis哨兵模式在Spring Boot项目中的使用与实践

什么是Redis哨兵模式?

Redis Sentinel(哨兵)是Redis官方提供的高可用性解决方案,主要用于管理Redis主从架构,实现自动故障转移监控通知。在没有哨兵模式之前,当Redis主节点宕机时,需要手动进行主从切换并更新应用程序配置,这对运维人员来说是极大的负担。有了哨兵模式,这些操作全部自动化,对客户端透明无缝切换,大大提高了系统的可靠性。

哨兵模式主要功能包括:

  • 监控:持续检查主节点和从节点是否正常运行
  • 通知:当监控的Redis实例出现问题时,向其他哨兵和客户端发送警报
  • 自动故障转移:主节点故障时自动选择一个从节点升级为主节点,并调整其他从节点指向新主节点

Spring Boot中配置Redis哨兵模式

添加依赖

pom.xml中添加Spring Boot Data Redis依赖,默认使用Lettuce客户端:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

如果需要使用Jedis客户端,还需添加:

<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>
</dependency>

配置文件设置

application.yml中配置Redis哨兵相关信息:

spring:redis:password: your-redis-password  # Redis认证密码sentinel:master: mymaster  # Redis主节点名称nodes:  # 哨兵节点列表- 192.168.1.110:26379- 192.168.1.111:26379- 192.168.1.112:26379lettuce:pool:  # 连接池配置(可选)max-active: 8max-idle: 8min-idle: 0max-wait: 5000ms

或者在application.properties中配置:

spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.1.110:26379,192.168.1.111:26379,192.168.1.112:26379
spring.redis.password=your-redis-password

自定义配置类

如果需要更精细的控制,可以创建自定义配置类:

@Configuration
public class RedisConfig {@Value("${spring.redis.sentinel.nodes}")private String sentinelNodes;@Value("${spring.redis.sentinel.master}")private String sentinelMaster;@Beanpublic RedisSentinelConfiguration redisSentinelConfiguration() {RedisSentinelConfiguration config = new RedisSentinelConfiguration();config.setMaster(sentinelMaster);config.setSentinels(Arrays.stream(sentinelNodes.split(",")).map(hostAndPort -> {String[] args = hostAndPort.split(":");return new RedisNode(args[0], Integer.parseInt(args[1]));}).collect(Collectors.toSet()));return config;}@Beanpublic LettuceConnectionFactory lettuceConnectionFactory(RedisSentinelConfiguration redisSentinelConfiguration) {LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder().readFrom(ReadFrom.MASTER_PREFERRED)  // 优先从主节点读取.build();return new LettuceConnectionFactory(redisSentinelConfiguration, clientConfig);}@Beanpublic RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(lettuceConnectionFactory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}

使用RedisTemplate操作Redis

配置完成后,可以在服务中使用RedisTemplate来操作Redis:

@Service
public class UserService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public void saveUser(String username, String password) {redisTemplate.opsForHash().put("users", username, password);}public String findUser(String username) {return (String) redisTemplate.opsForHash().get("users", username);}// 更多操作方法...
}

创建Controller提供API接口:

@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/add")public String addUser(String username, String password) {userService.saveUser(username, password);return "用户添加成功";}@GetMapping("/{username}")public String getUser(@PathVariable String username) {return userService.findUser(username);}
}

读写分离配置

Lettuce客户端支持读写分离策略,可以在配置中指定:

LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder().readFrom(ReadFrom.MASTER_PREFERRED)  // 优先从主节点读.build();

可选读策略包括:

  • MASTER:只从主节点读取
  • MASTER_PREFERRED:优先从主节点读取,主节点不可用时从副本读取
  • REPLICA:只从副本读取
  • REPLICA_PREFERRED:优先从副本读取,副本不可用时从主节点读取

常见问题与解决方案

  1. 认证失败错误:如果出现"NOAUTH HELLO must be called with the client already HELLO"错误,可能需要配置哨兵密码:
spring:redis:sentinel:password: your-sentinel-password
  1. 域名解析问题:如果哨兵返回的是域名而不是IP,需要在本地hosts文件中配置域名解析。

  2. 连接池配置:根据应用需求合理配置连接池参数,以提高性能并避免资源耗尽:

lettuce:pool:max-active: 8    # 最大连接数max-idle: 8      # 最大空闲连接数min-idle: 0      # 最小空闲连接数max-wait: 5000ms # 最大等待时间

最佳实践

  1. 哨兵节点数量:生产环境至少部署3个哨兵节点,以确保哨兵集群自身的高可用性。

  2. 网络规划:尽量让应用程序节点和Redis节点在相同的网络环境下,减少网络延迟。

  3. 监控告警:监控Redis实例和哨兵进程的状态,设置适当的告警机制。

  4. 定期演练:定期进行故障转移演练,验证系统的可靠性。

  5. 客户端兼容性:确保使用的客户端版本与Redis服务器版本兼容。

总结

Redis哨兵模式为Spring Boot应用程序提供了高可用的Redis解决方案,实现了自动故障转移和监控功能。通过合理的配置和使用,可以大大提升系统的稳定性和可靠性。在实际项目中,应根据业务需求选择合适的配置参数,并遵循最佳实践,才能充分发挥Redis哨兵模式的优势。


文章转载自:

http://ppbo71iD.fLqkp.cn
http://0ZELFYos.fLqkp.cn
http://aWccDkq2.fLqkp.cn
http://Bc3P4FmR.fLqkp.cn
http://tKcQIxTQ.fLqkp.cn
http://3Mrk6ZcV.fLqkp.cn
http://R8iND7nN.fLqkp.cn
http://ZN6qJZKT.fLqkp.cn
http://MufSxFZ6.fLqkp.cn
http://Lx4r4SI2.fLqkp.cn
http://SogRSq0U.fLqkp.cn
http://ylwjFn73.fLqkp.cn
http://mSBOMBne.fLqkp.cn
http://yfHz4SDo.fLqkp.cn
http://dQDpzMww.fLqkp.cn
http://tiuEVq7U.fLqkp.cn
http://0ia3aPGl.fLqkp.cn
http://2h5ogo9x.fLqkp.cn
http://A7oMm0sd.fLqkp.cn
http://d3ryCnIL.fLqkp.cn
http://31ls3rBC.fLqkp.cn
http://Et9wdm8W.fLqkp.cn
http://NxG8t5ww.fLqkp.cn
http://pnmGoJDR.fLqkp.cn
http://xZKg29NJ.fLqkp.cn
http://lFTmYiID.fLqkp.cn
http://3LwBjVqq.fLqkp.cn
http://Tz07tJZP.fLqkp.cn
http://cG4bl4eP.fLqkp.cn
http://LjLLfwFt.fLqkp.cn
http://www.dtcms.com/a/372372.html

相关文章:

  • [工作表控件13] 签名控件在合同审批中的应用
  • 【图像理解进阶】MobileViT-v3核心技术解析和应用场景说明
  • 前端拖拽功能实现全攻略
  • AI赋能软件开发|智能化编程实战与未来机会有哪些?
  • 335章:使用Scrapy框架构建分布式爬虫
  • Docker|“ssh: connect to host xxx.xxx.xxx.xxx port 8000: Connection refused“问题解决
  • OneCode 可视化揭秘系列(三):AI MCP驱动的智能工作流逻辑编排
  • 数据结构深度解析:二叉树的基本原理
  • Supabase02-速通
  • LLM学习:大模型基础——视觉大模型以及autodl使用
  • 嵌入式Secure Boot安全启动详解
  • 【倍增】P3901 数列找不同|普及+
  • 数据结构:堆
  • 继续优化基于树状数组的cuda前缀和
  • 数组常见算法
  • 数仓建模理论
  • 致远A8V5 9.0授权文件
  • 【New Phytologist】​​单细胞多组学揭示根毛对盐胁迫的特异性响应文献分享
  • MyBatis 拦截器让搞定监控、脱敏和权限控制
  • 20250907-0101:LangChain 核心价值补充
  • 论CMD、.NET、PowerShell、cmdlet四者关系
  • 从IFA展会看MOVA的“全维进阶”如何重新定义智能家居边界
  • SpringBoot 数据脱敏实战: 构建企业级敏感信息保护体系
  • 公链分析报告 - 模块化区块链1
  • 20250907-01:理解 LangChain 是什么 为什么诞生
  • 做一个鉴权系统
  • Javaweb - 14.5 Vue3 路由机制
  • 2.链表算法
  • Visual Studio Code的第一次安装
  • 基于 Visual Studio 2017 安装配置 GDAL 库的详细步骤