整合Redis集群的时候需要我们自己手动进行配置。

步骤:

  • 1)构建Spring boot项目 chapter06-rediscluster.添加如下依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
  • 2)编写配置文件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
  • 3)编写实体类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;
    }
}
  • 4)编写BookController。
@RestController
public 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<String, String> pos = stringRedisTemplate.opsForValue();
        pos.set("liubei","刘备");

        String liubei = pos.get("liubei");
        return liubei;
    }
}

到这里,大家把Docker下面两种集群搭建的方式搞完了,除了搭建环境比较麻烦外,其实在Spring Boot中访问redis集群很简单了。提醒注意的是搭建集群的时候对外公布的IP一定要写出宿主机的IP,否则在Spring Boot中访问会出问题。

文章名: Spring Boot整合Redis
文章链接:https://sjl511.cn/29.html
版权声明:版权归苏里,转载时请注明本文出处及文章链接。
最后修改:2020 年 06 月 04 日 05 : 54 PM
谢谢饲主了~~喵