欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springboot2.X集成redis集群(Lettuce)连接的方法

程序员文章站 2023-12-21 11:36:22
前提:搭建好redis集群环境,搭建方式请看: 1. 新建工程,pom.xml文件中添加redis支持

前提:搭建好redis集群环境,搭建方式请看:

1. 新建工程,pom.xml文件中添加redis支持

<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

2.配置application.properties

spring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384,127.0.0.1:6385
spring.redis.cluster.timeout=1000
spring.redis.cluster.max-redirects=3

3.      新建下面的两个类

@configuration
public class redisconfiguration {
  @resource
  private lettuceconnectionfactory mylettuceconnectionfactory;
  @bean
  public redistemplate<string, serializable> redistemplate() {
    redistemplate<string, serializable> template = new redistemplate<>();
    template.setkeyserializer(new stringredisserializer());
    template.setvalueserializer(new genericjackson2jsonredisserializer());
    template.setconnectionfactory(mylettuceconnectionfactory);
    return template;
  }
} 
@configuration
public class redisfactoryconfig {
  @autowired
  private environment environment;
  @bean
  public redisconnectionfactory mylettuceconnectionfactory() {
    map<string, object> source = new hashmap<string, object>();
    source.put("spring.redis.cluster.nodes", environment.getproperty("spring.redis.cluster.nodes"));
    source.put("spring.redis.cluster.timeout", environment.getproperty("spring.redis.cluster.timeout"));
    source.put("spring.redis.cluster.max-redirects", environment.getproperty("spring.redis.cluster.max-redirects"));
    redisclusterconfiguration redisclusterconfiguration;
    redisclusterconfiguration = new redisclusterconfiguration(new mappropertysource("redisclusterconfiguration", source));
    return new lettuceconnectionfactory(redisclusterconfiguration);
  }
} 

4. 执行测试

@springboottest
@runwith(springrunner.class)
public class redisconfigurationtest {

  @autowired
private redistemplate redistemplate;

@test
public void redistemplate() throws exception {

    redistemplate.opsforvalue().set("author", "damein_xym");
}

}

5. 验证,使用redis desktop manager 连接redis节点,查看里面的数据是否存在author,有如下显示,证明成功。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: