SpringBoot2.X整合Redis(集萬篇之總結(jié))
在學(xué)習(xí)過程當(dāng)中偶然遇到了redis,深深感受到他的強(qiáng)大之處。本篇博客就SpringBoot整合redis,
springboot1.X與2.X整合方式略有不同,本篇著重介紹2.X整合方法;
GitHub地址:
https://github.com/Guoxxin/springbootRedis.git
環(huán)境配置:
- Springboot 2.0.6
- redis 3.2.100
鏈接:https://pan.baidu.com/s/1rbZkjd8vtlm9-IHnIbhX8g
提取碼:wuly - redis可視化工具
鏈接:https://pan.baidu.com/s/1RKEkbs2qKQZ3PyABHaPTVQ
提取碼:20f4
項(xiàng)目結(jié)構(gòu)圖:

代碼實(shí)現(xiàn):
- pom.xml引入依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.yml文件配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
redis:
host: 127.0.0.1
port: 6379
password:
timeout: 3600ms #超時(shí)時(shí)間
jedis:
pool:
max-active: 8 #最大連接數(shù)
max-idle: 8 #最大空閑連接 默認(rèn)8
max-wait: -1ms #默認(rèn)-1 最大連接阻塞等待時(shí)間
min-idle: 0 #最小空閑連接
- 增加redis配置類 RedisConfig.java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置連接工廠
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認(rèn)使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會(huì)跑出異常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 設(shè)置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 生成一個(gè)默認(rèn)配置,通過config對(duì)象即可對(duì)緩存進(jìn)行自定義配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config.entryTtl(Duration.ofMinutes(1)) // 設(shè)置緩存的默認(rèn)過期時(shí)間,也是使用Duration設(shè)置
.disableCachingNullValues(); // 不緩存空值
// 設(shè)置一個(gè)初始化的緩存空間set集合
Set<String> cacheNames = new HashSet<>();
cacheNames.add("timeGroup");
cacheNames.add("user");
// 對(duì)每個(gè)緩存空間應(yīng)用不同的配置
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("timeGroup", config);
configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)// 使用自定義的緩存配置初始化一個(gè)cacheManager
.initialCacheNames(cacheNames) // 注意這兩句的調(diào)用順序,一定要先調(diào)用該方法設(shè)置初始化的緩存名,再初始化相關(guān)的配置
.withInitialCacheConfigurations(configMap)
.build();
return cacheManager;
}
}
4.redisTemplate具體使用方法
redisTemplate.opsForValue().set("你好啊","你好啊!!!");

ValueOperations vo = redisTemplate.opsForValue();
vo.set("所有的博客",all);

查詢緩存中的 “所有的博客” 緩存
@RequestMapping("/getRedisBlog")
public Result getredisBlog(){
ValueOperations operations = redisTemplate.opsForValue();
Object result = operations.get("所有的博客");
return new Result(200,"獲取成功",result);
}

ValueOperations接口說明
這個(gè)接口的實(shí)現(xiàn)類為DefaultValueOperations,default這個(gè)類同時(shí)繼承AbstractOperation,我們來看下這個(gè)類的構(gòu)造函數(shù):
DefaultValueOperations(RedisTemplate<K, V> template) {
super``(template);
}
這個(gè)類非公開的,需要傳入template來構(gòu)造。但是我們是無法訪問的。不過不要急,在RedisTemplate中,已經(jīng)提供了一個(gè)工廠方法:opsForValue()。這個(gè)方法會(huì)返回一個(gè)默認(rèn)的操作類。另外,我們可以直接通過ValueOperations operations = redisTemplate.opsForValue();來進(jìn)行注入。
opsForValue()集合使用說明
1). set(K key,V value)
新建緩存
redisTemplate.opsForValue().set("key","value");
2). get(Object key)
獲取緩存
edisTemplate.opsForValue().get("key");
具體可見 https://357029540.iteye.com/blog/2388965
講的特別詳細(xì)?。?!