Springboot2.X集成redis集群(Lettuce)連接的方法
前提:搭建好redis集群環(huán)境,搭建方式請看:http://m.dhdzp.com/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,有如下顯示,證明成功。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
淺談Java之Map 按值排序 (Map sort by value)
下面小編就為大家?guī)硪黄獪\談Java之Map 按值排序 (Map sort by value)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
java生成csv文件亂碼的解決方法示例 java導出csv亂碼
這篇文章主要介紹了java生成csv文件亂碼的解決方法,大家可以直接看下面的示例2014-01-01
教你安裝eclipse2021并配置內網(wǎng)maven中心倉庫的圖文詳解
本文能通過圖文并茂的形式給大家介紹安裝eclipse2021并配置內網(wǎng)maven中心倉庫的相關知識,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-09-09
SpringBoot查詢數(shù)據(jù)庫導出報表文件方式
這篇文章主要介紹了SpringBoot查詢數(shù)據(jù)庫導出報表文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
淺析Java常用API(Scanner,Random)匿名對象
這篇文章主要介紹了Java常用API(Scanner,Random)匿名對象,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-03-03

