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

时间:2021-05-20

前提:搭建好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:6385spring.redis.cluster.timeout=1000spring.redis.cluster.max-redirects=3

3. 新建下面的两个类

@Configurationpublic 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; }} @Configurationpublic 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 { @Autowiredprivate RedisTemplate redisTemplate;@Testpublic void redisTemplate() throws Exception { redisTemplate.opsForValue().set("author", "Damein_xym");}}

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

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章