springboot集成redis哨兵

首先配置linux中的哨兵配置文件

redis原来代码不用变,只需改一下application.properties中的配置

spring.redis.password=root
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.137.128:26380,192.168.137.128:26382,192.168.137.128:26384

master中一般默认名为mymaster,如果你没有改

哨兵节点用逗号隔开

 

可以通过以下步骤将Spring Boot集成Redis哨兵模式: 1. 添加Redis依赖:在`pom.xml`文件中添加Spring Data Redis的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis哨兵模式:在`application.properties`或`application.yml`中添加以下配置。 ```yaml spring.redis.sentinel.master=your_master_name spring.redis.sentinel.nodes=host1:port1,host2:port2,host3:port3 ``` 确保将上述配置中的 `your_master_name` 替换为你实际的 Redis 主节点名称,以及将 `host1:port1,host2:port2,host3:port3` 替换为实际的哨兵节点的主机和端口信息。 3. 创建Redis配置类:创建一个`RedisConfig`类,并使用`RedisSentinelConfiguration`进行配置。 ```java @Configuration public class RedisConfig { @Value("${spring.redis.sentinel.master}") private String sentinelMaster; @Value("${spring.redis.sentinel.nodes}") private String sentinelNodes; @Bean public RedisConnectionFactory redisConnectionFactory() { RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master(sentinelMaster); List<RedisNode> nodes = new ArrayList<>(); String[] hostsAndPorts = sentinelNodes.split(","); for (String hostAndPort : hostsAndPorts) { String[] parts = hostAndPort.split(":"); nodes.add(new RedisNode(parts[0].trim(), Integer.parseInt(parts[1].trim()))); } sentinelConfig.setSentinels(nodes); return new LettuceConnectionFactory(sentinelConfig); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); // 可以根据需要自定义序列化器等配置 return template; } } ``` 在上述配置类中,我们使用`RedisSentinelConfiguration`配置哨兵模式,并使用`LettuceConnectionFactory`作为连接工厂。 4. 使用Redis:现在你可以在Spring Boot应用程序中使用`RedisTemplate`来与Redis进行交互。例如: ```java @RestController public class MyController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/set") public void setValue() { redisTemplate.opsForValue().set("key", "value"); } @GetMapping("/get") public String getValue() { return (String) redisTemplate.opsForValue().get("key"); } } ``` 在上述示例中,我们注入了`RedisTemplate`,并使用其`opsForValue()`方法来进行常见的键值对操作。 这样就完成了Spring Boot集成Redis哨兵模式的配置。你可以根据实际需求使用更多的Redis功能和操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值