Spring?Caching配置緩存過期時(shí)間詳解
一、Spring Cache是什么?
它利用了AOP,實(shí)現(xiàn)了基于注解的緩存功能,并且進(jìn)行了合理的抽象,業(yè)務(wù)代碼不用關(guān)心底層是使用了什么緩存框架,只需要簡單地加一個(gè)注解,就能實(shí)現(xiàn)緩存功能了。
而且Spring Cache也提供了很多默認(rèn)的配置,用戶可以3秒鐘就使用上一個(gè)很不錯(cuò)的緩存功能。
工作流程:
- 使用Spring Cache分為很簡單的三步:添加依賴(springboot依賴包內(nèi)置),開啟緩存,加緩存注解。
- 每次調(diào)用該方法時(shí),都會(huì)檢查緩存以查看調(diào)用是否已經(jīng)運(yùn)行并且不必重復(fù)。雖然在大多數(shù)情況下,只聲明了一個(gè)緩存,但注釋允許指定多個(gè)名稱,以便使用多個(gè)緩存。在這種情況下,在調(diào)用該方法之前檢查每個(gè)緩存 - 如果至少命中一個(gè)緩存,則返回關(guān)聯(lián)的值。
- 會(huì)觸發(fā)一個(gè)后置處理,這會(huì)掃描每一個(gè)spring bean,查看是否已經(jīng)存在緩存。如果找到了,就會(huì)自動(dòng)創(chuàng)建一個(gè)代理攔截方法調(diào)用,使用緩存的bean執(zhí)行處理。
特性:
- 緩存數(shù)據(jù)是存在redis
- 默認(rèn)永不過期
- key-value鍵、值隊(duì)存儲(chǔ)
二、使用步驟
開啟基于注解的緩存
- 在啟動(dòng)類添加以下注解
@EnableCaching
配置緩存
- 在需要緩存數(shù)據(jù)的方法上面添加
@Cacheable注解,即可緩存這個(gè)方法的返回值。
@Cacheable(value = "DefaultKeyTest", keyGenerator = "simpleKeyGenerator", /*cacheNames = API_DETAIL_KEY_PREFIX, key = "target.redisApiDetailKeyPrefix + ':' + #appCode",*/ unless = "#result == null")
public OpenApiDetailVo findByAppCode(String appCode) {
return openApiAuthService.queryDetail(appCode);
}
三、解決方案
方案一:通過編寫config設(shè)置緩存相關(guān)項(xiàng)
- 要指定 key 的過期時(shí)間,只需要getRedisCacheConfigurationMap方法中添加就可以。
@Configuration
public class RedisCacheConfig {
@Bean
public KeyGenerator simpleKeyGenerator() {
return (o, method, objects) -> {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getSimpleName());
stringBuilder.append(".");
stringBuilder.append(method.getName());
stringBuilder.append("[");
for (Object obj : objects) {
stringBuilder.append(obj.toString());
}
stringBuilder.append("]");
return stringBuilder.toString();
};
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(600), // 默認(rèn)策略,未配置的 key 會(huì)使用這個(gè)
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
redisCacheConfigurationMap.put("UserInfoList", this.getRedisCacheConfigurationWithTtl(3000));
redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000));
return redisCacheConfigurationMap;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}
- 下面給出三種案例
// 3000秒
@Cacheable(value = "UserInfoList", keyGenerator = "simpleKeyGenerator")
// 18000秒
@Cacheable(value = "UserInfoListAnother", keyGenerator = "simpleKeyGenerator")
// 600秒,未指定的key,使用默認(rèn)策略
@Cacheable(value = "DefaultKeyTest", keyGenerator = "simpleKeyGenerator")
方案二:通過配置文件
spring:
# maximumSize:配置緩存的最大條數(shù),當(dāng)快要達(dá)到容量上限的時(shí)候,緩存管理器會(huì)根據(jù)一定的策略將部分緩存項(xiàng)移除。
# expireAfterAccess:配置緩存項(xiàng)的過期機(jī)制,緩存項(xiàng)固定30秒將會(huì)過期,從而被移除。
cache:
caffeine:
spec: maximumSize=500, expireAfterAccess=30s
type: caffeine
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring集成webSocket頁面訪問404問題的解決方法
這篇文章主要介紹了Spring集成webSocket頁面訪問404問題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Nginx+SpringCloud Gateway搭建項(xiàng)目訪問環(huán)境
本文主要介紹了Nginx+SpringCloud Gateway搭建項(xiàng)目訪問環(huán)境,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Spring中ClassPathXmlApplicationContext類的使用詳解
這篇文章主要介紹了Spring中ClassPathXmlApplicationContext類的使用詳解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
java實(shí)現(xiàn)隨機(jī)輸出300題四則運(yùn)算
本文主要介紹了java實(shí)現(xiàn)隨機(jī)輸出300題四則運(yùn)算實(shí)例,具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03

