上一篇:SpringBoot如何整合Redis(单机版)? | 带你读《SpringBoot实战教程》之三十二
下一篇:SpringBoot如何集成MongoDB? | 带你读《SpringBoot实战教程》之三十四
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。
SpringBoot整合Redis集群
以上一节案例为例:
添加依赖:
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
注释单机版全局配置,添加集群配置:
spring.redis.cluster.nodes=192.168.25.128:7550, 192.168.25.128:7551, 192.168.25.128:7552, 192.168.25.128:7553, 192.168.25.128:7554, 192.168.25.128:7555
创建一个配置类:
@Configuration
public class RedisConfig {
@Value("${spring.redis.cluster.nodes}")
private String redisNode;
@Bean
public JedisCluster getJedisCluster() {
String[] redisnodes = redisNodes.split(",");
Set<HostAndPort> nodes = new HashSet<>();
for(String node:redisnodes) {
String[] arr=node.split(":");
HostAndPort hostAndPort = new HostAndPort(arr[0], Integer.parseInt(arr[1]));
nodes.add(hostAndPort);
}
JedisCluster cluster = new JedisCluster(nodes);
return cluster;
}
}
UserService:
public String findRedis();
UserServiceImpl:
@Autowried
private JedisCluster jedisCluster;
@Override
public String findRedis() {
jedisCluster.set("haha", "kele");
return jedisCluster.get("haha");
}
UserController:
@RequestMapping("/redis")
@ResponseBody
public String findRedis() {
return userService.findRedis();
}
执行结果: