Java SpringCache+Redis緩存數(shù)據(jù)詳解
前言
這幾天學(xué)習(xí)谷粒商城又再次的回顧了一次SpringCache,之前在學(xué)習(xí)谷粒學(xué)院的時候其實已經(jīng)學(xué)習(xí)了一次了!??!
這里就對自己學(xué)過來的內(nèi)容進行一次的總結(jié)和歸納?。?!
一、什么是SpringCache
- Spring Cache 是一個非常優(yōu)秀的緩存組件。自Spring 3.1起,提供了類似于@Transactional注解事務(wù)的注解Cache支持,且提供了Cache抽象,方便切換各種底層Cache(如:redis)
- 使用Spring Cache的好處:
- 提供基本的Cache抽象,方便切換各種底層Cache;
- 通過注解Cache可以實現(xiàn)類似于事務(wù)一樣,緩存邏輯透明的應(yīng)用到我們的業(yè)務(wù)代碼上,且只需要更少的代碼就可以完成;
- 提供事務(wù)回滾時也自動回滾緩存;
- 支持比較復(fù)雜的緩存邏輯;
二、項目集成Spring Cache + Redis
- 依賴
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
開啟@EnableCaching
1、配置方式
①第一種:配置類
@Configuration
@EnableCaching
public class RedisConfig {
/**
* 自定義key規(guī)則
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 設(shè)置RedisTemplate規(guī)則
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解決查詢緩存轉(zhuǎn)換異常的問題
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會跑出異常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//序列號key value
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 設(shè)置CacheManager緩存規(guī)則
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解決查詢緩存轉(zhuǎn)換異常的問題
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解決亂碼的問題),過期時間600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
或
②結(jié)合配置+配置文件
spring:
cache:
#指定緩存類型為redis
type: redis
redis:
# 指定redis中的過期時間為1h
time-to-live: 3600000
key-prefix: CACHE_ #緩存key前綴
use-key-prefix: true #是否開啟緩存key前綴
cache-null-values: true #緩存空值,解決緩存穿透問題
默認使用jdk進行序列化(可讀性差),默認ttl為-1永不過期,自定義序列化方式為JSON需要編寫配置類
@Configuration
@EnableConfigurationProperties(CacheProperties.class)//拿到Redis在配置文件的配置
public class MyCacheConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
//獲取到配置文件中的配置信息
CacheProperties.Redis redisProperties = cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();
//指定緩存序列化方式為json
config = config.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
//設(shè)置配置文件中的各項配置,如過期時間
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
說明:
第一種,全自定義配置第二種,簡單配置+自定義配置value值json轉(zhuǎn)義
- 對redis進行配置
#redis配置 spring.redis.host=47.120.237.184 spring.redis.port=6379 spring.redis.password=ach2ng@123356 spring.redis.database= 0 spring.redis.timeout=1800000 #redis池設(shè)置 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 #最大阻塞等待時間(負數(shù)表示沒限制) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0
三、使用Spring Cache
@Cacheable
根據(jù)方法對其返回結(jié)果進行緩存,下次請求時,如果緩存存在,則直接讀取緩存數(shù)據(jù)返回;如果緩存不存在,則執(zhí)行方法,并把返回的結(jié)果存入緩存中。一般用在查詢方法上。
| 屬性/方法名 | 解釋 |
|---|---|
| value | 緩存名,必填,它指定了你的緩存存放在哪塊分區(qū),可多指定,如{"catagory","xxxx",....} |
| cacheNames | 與 value 差不多,二選一即可 |
| key | 可選屬性,可以使用 SpEL 標簽自定義緩存的key,如:#root.methodName【用方法名作為key】 |
| sync | 默認false,為true時,會讓操作被同步保護,可避免緩存擊穿問題 |
@CachePut
使用該注解標志的方法,每次都會執(zhí)行,并將結(jié)果存入指定的緩存中。其他方法可以直接從響應(yīng)的緩存中讀取緩存數(shù)據(jù),而不需要再去查詢數(shù)據(jù)庫。一般用在新增方法上。
| 屬性/方法名 | |
|---|---|
| value | 緩存名,必填,它指定了你的緩存存放在==哪塊分區(qū),==可多指定,如{"catagory","xxxx",....} |
| cacheNames | 與 value 差不多,二選一即可 |
| key | 可選屬性,可以使用 SpEL 標簽自定義緩存的key |
@CacheEvict
使用該注解標志的方法,會清空指定的緩存。一般用在更新或者刪除方法上
| 屬性/方法名 | 解釋 |
|---|---|
| value | 緩存名,必填,它指定了你的緩存存放在==哪塊分區(qū),==可多指定,如{"catagory","xxxx",....} |
| cacheNames | 與 value 差不多,二選一即可 |
| key | 可選屬性,可以使用 SpEL 標簽自定義緩存的key key如果是字符串"''",【請加上單引號】 |
| allEntries | 是否清空所有緩存,默認為 false。如果指定為 true,則方法調(diào)用后將立即清空所有的緩存 allEntries = true,會對刪除value分區(qū)里的所有數(shù)據(jù) |
| beforeInvocation | 是否在方法執(zhí)行前就清空,默認為 false。如果指定為 true,則在方法執(zhí)行前就會清空緩存 |
@Caching
可組合使用以上注解,如:
//組合了刪除緩存的@CacheEvict注解,同時刪除兩個
@Cacheing(evict=
{@CacheEvict(value="a"),key="'getLists'"}),
{@CacheEvict(value="b"),key="'getArr'"})
)
使用舉例 失效模式: 更新操作后,刪除緩存 雙寫模式: 更新操作后,新增緩存,掩蓋

四、SpringCache原理與不足
1、讀模式
緩存穿透:
查詢一個null數(shù)據(jù)。
解決方案:緩存空數(shù)據(jù)
可通過spring.cache.redis.cache-null-values=true
緩存擊穿:
大量并發(fā)進來同時查詢一個正好過期的數(shù)據(jù)。
解決方案: 加鎖 ? 默認是無加鎖的;
使用sync = true來解決擊穿問題
緩存雪崩:
大量的key同時過期。
解決方案:加隨機時間,time-to-live: 3600000。
2、寫模式:(緩存與數(shù)據(jù)庫一致)
- 讀寫加鎖。
- 引入Canal,感知到MySQL的更新去更新Redis
- 讀多寫多,直接去數(shù)據(jù)庫查詢就行
五、總結(jié)
常規(guī)數(shù)據(jù)(讀多寫少,即時性,一致性要求不高的數(shù)據(jù),完全可以使用Spring-Cache):
寫模式(只要緩存的數(shù)據(jù)有過期時間就足夠了)
特殊數(shù)據(jù):
特殊設(shè)計(讀寫鎖、redis分布鎖等
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
idea新建springboot項目pom文件報錯問題及解決
這篇文章主要介紹了idea新建springboot項目pom文件報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
本地MinIO存儲服務(wù)Java遠程調(diào)用上傳文件的操作過程
MinIO是一款高性能、分布式的對象存儲系統(tǒng),它可以100%的運行在標準硬件上,即X86等低成本機器也能夠很好的運行MinIO,這篇文章主要介紹了本地MinIO存儲服務(wù)Java遠程調(diào)用上傳文件的操作過程,需要的朋友可以參考下2023-11-11
詳解mybatis-plus配置找不到Mapper接口路徑的坑
這篇文章主要介紹了詳解mybatis-plus配置找不到Mapper接口路徑的坑,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

