spring boot集成redis哨兵模式(一主二从)
Spring Boot 集成 Redis 哨兵模式(一主二从),是指在 Spring Boot 应用中配置并连接采用哨兵机制的 Redis 集群。该集群包含 1 个主节点负责处理读写操作,2 个从节点通过复制主节点数据实现备份,而哨兵节点则持续监控主从节点状态,当主节点故障时自动将从节点晋升为主节点,保障 Redis 服务的高可用。通过 Spring Boot 的配置类或配置文件指定哨兵节点信息、主节点名称等参数,可实现应用与该 Redis 集群的无缝集成,既利用了 Redis 的高性能缓存能力,又借助哨兵模式提升了系统的稳定性和容错性,适用于对数据可靠性和服务连续性有较高要求的业务场景。
- 搭建redis主从环境
- sprint boot集成redis
- Nginx代理Redis哨兵模式
一、环境介绍
- spring boot 2.5.3
- spring boot data redis 2.5.3
- lettuce 6.1.4.RELEASE
- commons-pool2 2.2.9.0
二、application.yml配置
说明
1. 使用约定大于配置的模式实现spring boot redis哨兵模式
2. 关于怎么样创建spring boot工程,可以自行网络一下,教程多如牛毛
3. 如果配置文件中使用Nginx代理的哨兵模式,后续由于redis迁移、配置变更等问题均不会影响业务应用的正常运行。
server:
port: 8090
spring:
redis:
# 数据库(默认为0号库)
# database: 2
# 密码(默认空),操作redis需要使用的密码
password: jwssw
# 端口号
# port: 6379
#连接超时时间(毫秒)
timeout: 10000ms
sentinel:
master: mymaster
nodes:
- 192.168.229.200:26379
- 192.168.229.201:26379
- 192.168.229.202:26379
# 操作sentinel时需要提供的密码
password: jwssw
# 使用lettuce配置
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 200
# 连接池中的最大空闲连接
max-idle: 20
# 连接池中的最小空闲连接
min-idle: 5
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
三、redis配置类
package cn.jwssw.ddd.infrastructure.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* 类描述:redis配置类
*
* @version 1.0
* @date 2021/8/10 12:50
* @since JDK 8
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 定义redis模板
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 创建序列号对象
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(<

本文介绍了如何在SpringBoot项目中配置并集成Redis哨兵模式,以实现高可用的Redis连接。在配置过程中,遇到无法连接Redis的权限问题,通过检查sentinel配置文件和application.yml中的密码设置,解决了该问题。此外,还提供了详细的配置文件内容和测试类代码供参考。
最低0.47元/天 解锁文章
264





