那么今日份《峰哥说技术》继续
Spring Boot 操作Redis集群
整合集群和整合单机版不一样,整合Redis集群的时候我们自己手动进行配置类,也可以不写配置类。其实也不难。参照峰哥笔记你也可以完成的。
实施步骤
01.构建Spring boot项目 chapter06-rediscluster。
添加如下依赖。
org.springframework.boot spring-boot-starter-data-redis io.lettuce
lettuce-coreredis.clients
jedisorg.apache.commons
commons-pool2
02.编写配置文件application.yml。
spring: redis: cluster: nodes: 192.168.21.134:7000,192.168.21.134:7001,192.168.21.134:7002,192.168.21.134:7003,192.168.21.134:7004,192.168.21.134:7005 database: 0 jedis: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1
03.编写实体类Book,注意序列化。
public class Book implements Serializable { private String name; private String author; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }}
04.编写BookController。
@RestControllerpublic class BookController { @Autowired RedisTemplate redisTemplate; @Autowired StringRedisTemplate stringRedisTemplate; @GetMapping("/book") public Book book(){ Book book=new Book(); book.setAuthor("路遥"); book.setName("平凡的世界"); ValueOperations ops = redisTemplate.opsForValue(); ops.set("book",book); Book book1 = (Book) ops.get("book"); return book1; } @GetMapping("/test") public String test(){ ValueOperations pos = stringRedisTemplate.opsForValue(); pos.set("liubei","刘备"); String liubei = pos.get("liubei"); return liubei; }}
05.测试即可。
分别在浏览器输入http://localhost:8080/test和http://localhost:8080/book
到这里,峰哥就带着大家把Docker下面两种集群搭建的方式搞完了,除了搭建环境比较麻烦外,其实在Spring Boot中访问redis集群很简单了。提醒小伙伴注意的是搭建集群的时候对外公布的IP一定要写出宿主机的IP,否则在Spring Boot中访问会出问题。这个问题当年峰哥也是研究了好久才解决的。