Springboot2.X集成redis集群(Lettuce)連接的方法
前提:搭建好redis集群環(huán)境,搭建方式請(qǐng)看: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. 新建下面的兩個(gè)類
@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í)行測(cè)試
@SpringBootTest @RunWith(SpringRunner.class) public class RedisConfigurationTest { @Autowired private RedisTemplate redisTemplate; @Test public void redisTemplate() throws Exception { redisTemplate.opsForValue().set("author", "Damein_xym"); } }
5. 驗(yàn)證,使用Redis Desktop Manager 連接redis節(jié)點(diǎn),查看里面的數(shù)據(jù)是否存在author,有如下顯示,證明成功。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
原生java代碼實(shí)現(xiàn)碼云第三方驗(yàn)證登錄的示例代碼
這篇文章主要介紹了原生java代碼實(shí)現(xiàn)碼云第三方驗(yàn)證登錄的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04Idea入門(mén)教程之一分鐘創(chuàng)建一個(gè)Java工程
idea作為Java開(kāi)發(fā)最好用的編寫(xiě)代碼軟件之一,首先進(jìn)行的就是工程的創(chuàng)建,這篇文章主要給大家介紹了關(guān)于Idea入門(mén)教程之一分鐘創(chuàng)建一個(gè)Java工程的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07

SpringBoot整合之SpringBoot整合MongoDB的詳細(xì)步驟

SpringBoot RestTemplate請(qǐng)求日志打印方式

微信公眾號(hào)獲取access_token的方法實(shí)例分析

springboot解決Class path contains multiple