温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-09 19:36:47 来源:脚本之家 阅读:449 作者:Damein_xym 栏目:编程语言

前提:搭建好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,有如下显示,证明成功。

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI