Springboot2.X集成redis集群(Lettuce)連接的方法
前提:搭建好redis集群環(huán)境,搭建方式請看:http://www.dbjr.com.cn/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. 執(zhí)行測試
@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節(jié)點,查看里面的數(shù)據(jù)是否存在author,有如下顯示,證明成功。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
原生java代碼實現(xiàn)碼云第三方驗證登錄的示例代碼
這篇文章主要介紹了原生java代碼實現(xiàn)碼云第三方驗證登錄的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04Idea入門教程之一分鐘創(chuàng)建一個Java工程
idea作為Java開發(fā)最好用的編寫代碼軟件之一,首先進行的就是工程的創(chuàng)建,這篇文章主要給大家介紹了關(guān)于Idea入門教程之一分鐘創(chuàng)建一個Java工程的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-07-07

SpringBoot整合之SpringBoot整合MongoDB的詳細步驟

SpringBoot RestTemplate請求日志打印方式

springboot解決Class path contains multiple