Redis

关注公众号 jb51net

关闭
首页 > 数据库 > Redis > springboot使用redis哨兵模式

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

作者:知识浅谈

Redis哨兵模式为SpringBoot项目提供高可用Redis管理,实现自动故障转移与监控,通过配置依赖、参数及最佳实践(如哨兵节点数量、网络规划),可提升系统稳定性与可靠性,本文给大家介绍Redis哨兵模式在Spring Boot项目中的使用与实践,感兴趣的朋友跟随小编一起看看吧

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

什么是Redis哨兵模式?

Redis Sentinel(哨兵)是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:26379
    lettuce:
      pool:  # 连接池配置(可选)
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-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;
    @Bean
    public 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;
    }
    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory(RedisSentinelConfiguration redisSentinelConfiguration) {
        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                .readFrom(ReadFrom.MASTER_PREFERRED)  // 优先从主节点读取
                .build();
        return new LettuceConnectionFactory(redisSentinelConfiguration, clientConfig);
    }
    @Bean
    public 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 {
    @Autowired
    private 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 {
    @Autowired
    private 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();

可选读策略包括:

常见问题与解决方案

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

最佳实践

总结

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

到此这篇关于Redis哨兵模式在Spring Boot项目中的使用与实践完全指南的文章就介绍到这了,更多相关springboot使用redis哨兵模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文