欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-07-11 08:41:22|栏目:JAVA代码|点击:

前提:搭建好redis集群环境,搭建方式请看:https://www.jb51.net/article/143749.htm

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,有如下显示,证明成功。

上一篇:零基础写Java知乎爬虫之获取知乎编辑推荐内容

栏    目:JAVA代码

下一篇:关于spring中定时器的使用教程

本文标题:Springboot2.X集成redis集群(Lettuce)连接的方法

本文地址:http://www.codeinn.net/misctech/155645.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有