問題描述
Spring Cache提供的@Cacheable注解不支持配置過期時(shí)間,還有緩存的自動(dòng)刷新诱桂。
我們可以通過配置CacheManneg來配置默認(rèn)的過期時(shí)間和針對每個(gè)緩存容器(value)單獨(dú)配置過期時(shí)間帘瞭,但是總是感覺不太靈活淑掌。下面是一個(gè)示例:
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager= new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(60);
Map<String,Long> expiresMap=new HashMap<>();
expiresMap.put("Product",5L);
cacheManager.setExpires(expiresMap);
return cacheManager;
}
我們想在注解上直接配置過期時(shí)間和自動(dòng)刷新時(shí)間,就像這樣:
@Cacheable(value = "people#120#90", key = "#person.id")
public Person findOne(Person person) {
Person p = personRepository.findOne(person.getId());
System.out.println("為id蝶念、key為:" + p.getId() + "數(shù)據(jù)做了緩存");
return p;
}
value屬性上用#號隔開抛腕,第一個(gè)是原始的緩存容器名稱,第二個(gè)是緩存的有效時(shí)間媒殉,第三個(gè)是緩存的自動(dòng)刷新時(shí)間担敌,單位都是秒。
緩存的有效時(shí)間和自動(dòng)刷新時(shí)間支持SpEl表達(dá)式廷蓉,支持在配置文件中配置全封,如:
@Cacheable(value = "people#${select.cache.timeout:1800}#${select.cache.refresh:600}", key = "#person.id", sync = true)//3
public Person findOne(Person person) {
Person p = personRepository.findOne(person.getId());
System.out.println("為id、key為:" + p.getId() + "數(shù)據(jù)做了緩存");
return p;
}
解決思路
查看源碼你會(huì)發(fā)現(xiàn)緩存最頂級的接口就是CacheManager和Cache接口桃犬。
CacheManager說明
CacheManager功能其實(shí)很簡單就是管理cache刹悴,接口只有兩個(gè)方法,根據(jù)容器名稱獲取一個(gè)Cache攒暇。還有就是返回所有的緩存名稱土匀。
public interface CacheManager {
/**
* 根據(jù)名稱獲取一個(gè)Cache(在實(shí)現(xiàn)類里面是如果有這個(gè)Cache就返回,沒有就新建一個(gè)Cache放到Map容器中)
* @param name the cache identifier (must not be {@code null})
* @return the associated cache, or {@code null} if none found
*/
Cache getCache(String name);
/**
* 返回一個(gè)緩存名稱的集合
* @return the names of all caches known by the cache manager
*/
Collection<String> getCacheNames();
}
Cache說明
Cache接口主要是操作緩存的形用。get根據(jù)緩存key從緩存服務(wù)器獲取緩存中的值就轧,put根據(jù)緩存key將數(shù)據(jù)放到緩存服務(wù)器,evict根據(jù)key刪除緩存中的數(shù)據(jù)田度。
public interface Cache {
ValueWrapper get(Object key);
void put(Object key, Object value);
void evict(Object key);
...
}
請求步驟
- 請求進(jìn)來妒御,在方法上面掃描@Cacheable注解,那么會(huì)觸發(fā)org.springframework.cache.interceptor.CacheInterceptor緩存的攔截器镇饺。
- 然后會(huì)調(diào)用CacheManager的getCache方法携丁,獲取Cache,如果沒有(第一次訪問)就新建一Cache并返回兰怠。
- 根據(jù)獲取到的Cache去調(diào)用get方法獲取緩存中的值。RedisCache這里有個(gè)bug李茫,源碼是先判斷key是否存在揭保,再去緩存獲取值,在高并發(fā)下有bug魄宏。
代碼分析
在最上面我們說了Spring Cache可以通過配置CacheManager來配置過期時(shí)間秸侣。那么這個(gè)過期時(shí)間是在哪里用的呢?設(shè)置默認(rèn)的時(shí)間setDefaultExpiration,根據(jù)特定名稱設(shè)置有效時(shí)間setExpires味榛,獲取一個(gè)緩存名稱(value屬性)的有效時(shí)間computeExpiration椭坚,真正使用有效時(shí)間是在createCache方法里面,而這個(gè)方法是在父類的getCache方法調(diào)用搏色。通過RedisCacheManager源碼我們看到:
// 設(shè)置默認(rèn)的時(shí)間
public void setDefaultExpiration(long defaultExpireTime) {
this.defaultExpiration = defaultExpireTime;
}
// 根據(jù)特定名稱設(shè)置有效時(shí)間
public void setExpires(Map<String, Long> expires) {
this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null);
}
// 獲取一個(gè)key的有效時(shí)間
protected long computeExpiration(String name) {
Long expiration = null;
if (expires != null) {
expiration = expires.get(name);
}
return (expiration != null ? expiration.longValue() : defaultExpiration);
}
@SuppressWarnings("unchecked")
protected RedisCache createCache(String cacheName) {
// 調(diào)用了上面的方法獲取緩存名稱的有效時(shí)間
long expiration = computeExpiration(cacheName);
// 創(chuàng)建了Cache對象善茎,并使用了這個(gè)有效時(shí)間
return new RedisCache(cacheName, (usePrefix ? cachePrefix.prefix(cacheName) : null), redisOperations, expiration,
cacheNullValues);
}
// 重寫父類的getMissingCache。去創(chuàng)建Cache
@Override
protected Cache getMissingCache(String name) {
return this.dynamic ? createCache(name) : null;
}
AbstractCacheManager父類源碼:
// 根據(jù)名稱獲取Cache如果沒有調(diào)用getMissingCache方法频轿,生成新的Cache垂涯,并將其放到Map容器中去。
@Override
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache != null) {
return cache;
}
else {
// Fully synchronize now for missing cache creation...
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
// 如果沒找到Cache調(diào)用該方法航邢,這個(gè)方法默認(rèn)返回值NULL由子類自己實(shí)現(xiàn)耕赘。上面的就是子類自己實(shí)現(xiàn)的方法
cache = getMissingCache(name);
if (cache != null) {
cache = decorateCache(cache);
this.cacheMap.put(name, cache);
updateCacheNames(name);
}
}
return cache;
}
}
}
由此這個(gè)有效時(shí)間的設(shè)置關(guān)鍵就是在getCache方法上,這里的name參數(shù)就是我們注解上的value屬性膳殷。所以在這里解析這個(gè)特定格式的名稱我就可以拿到配置的過期時(shí)間和刷新時(shí)間操骡。getMissingCache方法里面在新建緩存的時(shí)候?qū)⑦@個(gè)過期時(shí)間設(shè)置進(jìn)去,生成的Cache對象操作緩存的時(shí)候就會(huì)帶上我們的配置的過期時(shí)間赚窃,然后過期就生效了册招。解析SpEL表達(dá)式獲取配置文件中的時(shí)間也在也一步完成。
CustomizedRedisCacheManager源碼:
package com.xiaolyuh.redis.cache;
import com.xiaolyuh.redis.cache.helper.SpringContextHolder;
import com.xiaolyuh.redis.utils.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
/**
* 自定義的redis緩存管理器
* 支持方法上配置過期時(shí)間
* 支持熱加載緩存:緩存即將過期時(shí)主動(dòng)刷新緩存
*
* @author yuhao.wang
*/
public class CustomizedRedisCacheManager extends RedisCacheManager {
private static final Logger logger = LoggerFactory.getLogger(CustomizedRedisCacheManager.class);
/**
* 父類cacheMap字段
*/
private static final String SUPER_FIELD_CACHEMAP = "cacheMap";
/**
* 父類dynamic字段
*/
private static final String SUPER_FIELD_DYNAMIC = "dynamic";
/**
* 父類cacheNullValues字段
*/
private static final String SUPER_FIELD_CACHENULLVALUES = "cacheNullValues";
/**
* 父類updateCacheNames方法
*/
private static final String SUPER_METHOD_UPDATECACHENAMES = "updateCacheNames";
/**
* 緩存參數(shù)的分隔符
* 數(shù)組元素0=緩存的名稱
* 數(shù)組元素1=緩存過期時(shí)間TTL
* 數(shù)組元素2=緩存在多少秒開始主動(dòng)失效來強(qiáng)制刷新
*/
private static final String SEPARATOR = "#";
/**
* SpEL標(biāo)示符
*/
private static final String MARK = "$";
RedisCacheManager redisCacheManager = null;
@Autowired
DefaultListableBeanFactory beanFactory;
public CustomizedRedisCacheManager(RedisOperations redisOperations) {
super(redisOperations);
}
public CustomizedRedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames) {
super(redisOperations, cacheNames);
}
public RedisCacheManager getInstance() {
if (redisCacheManager == null) {
redisCacheManager = SpringContextHolder.getBean(RedisCacheManager.class);
}
return redisCacheManager;
}
@Override
public Cache getCache(String name) {
String[] cacheParams = name.split(SEPARATOR);
String cacheName = cacheParams[0];
if (StringUtils.isBlank(cacheName)) {
return null;
}
// 有效時(shí)間考榨,初始化獲取默認(rèn)的有效時(shí)間
Long expirationSecondTime = getExpirationSecondTime(cacheName, cacheParams);
// 自動(dòng)刷新時(shí)間跨细,默認(rèn)是0
Long preloadSecondTime = getExpirationSecondTime(cacheParams);
// 通過反射獲取父類存放緩存的容器對象
Object object = ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHEMAP);
if (object != null && object instanceof ConcurrentHashMap) {
ConcurrentHashMap<String, Cache> cacheMap = (ConcurrentHashMap<String, Cache>) object;
// 生成Cache對象,并將其保存到父類的Cache容器中
return getCache(cacheName, expirationSecondTime, preloadSecondTime, cacheMap);
} else {
return super.getCache(cacheName);
}
}
/**
* 獲取過期時(shí)間
*
* @return
*/
private long getExpirationSecondTime(String cacheName, String[] cacheParams) {
// 有效時(shí)間河质,初始化獲取默認(rèn)的有效時(shí)間
Long expirationSecondTime = this.computeExpiration(cacheName);
// 設(shè)置key有效時(shí)間
if (cacheParams.length > 1) {
String expirationStr = cacheParams[1];
if (!StringUtils.isEmpty(expirationStr)) {
// 支持配置過期時(shí)間使用EL表達(dá)式讀取配置文件時(shí)間
if (expirationStr.contains(MARK)) {
expirationStr = beanFactory.resolveEmbeddedValue(expirationStr);
}
expirationSecondTime = Long.parseLong(expirationStr);
}
}
return expirationSecondTime;
}
/**
* 獲取自動(dòng)刷新時(shí)間
*
* @return
*/
private long getExpirationSecondTime(String[] cacheParams) {
// 自動(dòng)刷新時(shí)間冀惭,默認(rèn)是0
Long preloadSecondTime = 0L;
// 設(shè)置自動(dòng)刷新時(shí)間
if (cacheParams.length > 2) {
String preloadStr = cacheParams[2];
if (!StringUtils.isEmpty(preloadStr)) {
// 支持配置刷新時(shí)間使用EL表達(dá)式讀取配置文件時(shí)間
if (preloadStr.contains(MARK)) {
preloadStr = beanFactory.resolveEmbeddedValue(preloadStr);
}
preloadSecondTime = Long.parseLong(preloadStr);
}
}
return preloadSecondTime;
}
/**
* 重寫父類的getCache方法,真假了三個(gè)參數(shù)
*
* @param cacheName 緩存名稱
* @param expirationSecondTime 過期時(shí)間
* @param preloadSecondTime 自動(dòng)刷新時(shí)間
* @param cacheMap 通過反射獲取的父類的cacheMap對象
* @return Cache
*/
public Cache getCache(String cacheName, long expirationSecondTime, long preloadSecondTime, ConcurrentHashMap<String, Cache> cacheMap) {
Cache cache = cacheMap.get(cacheName);
if (cache != null) {
return cache;
} else {
// Fully synchronize now for missing cache creation...
synchronized (cacheMap) {
cache = cacheMap.get(cacheName);
if (cache == null) {
// 調(diào)用我們自己的getMissingCache方法創(chuàng)建自己的cache
cache = getMissingCache(cacheName, expirationSecondTime, preloadSecondTime);
if (cache != null) {
cache = decorateCache(cache);
cacheMap.put(cacheName, cache);
// 反射去執(zhí)行父類的updateCacheNames(cacheName)方法
Class<?>[] parameterTypes = {String.class};
Object[] parameters = {cacheName};
ReflectionUtils.invokeMethod(getInstance(), SUPER_METHOD_UPDATECACHENAMES, parameterTypes, parameters);
}
}
return cache;
}
}
}
/**
* 創(chuàng)建緩存
*
* @param cacheName 緩存名稱
* @param expirationSecondTime 過期時(shí)間
* @param preloadSecondTime 制動(dòng)刷新時(shí)間
* @return
*/
public CustomizedRedisCache getMissingCache(String cacheName, long expirationSecondTime, long preloadSecondTime) {
logger.info("緩存 cacheName:{}掀鹅,過期時(shí)間:{}, 自動(dòng)刷新時(shí)間:{}", cacheName, expirationSecondTime, preloadSecondTime);
Boolean dynamic = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_DYNAMIC);
Boolean cacheNullValues = (Boolean) ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHENULLVALUES);
return dynamic ? new CustomizedRedisCache(cacheName, (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null),
this.getRedisOperations(), expirationSecondTime, preloadSecondTime, cacheNullValues) : null;
}
}
那自動(dòng)刷新時(shí)間呢散休?
在RedisCache的屬性里面沒有刷新時(shí)間,所以我們繼承該類重寫我們自己的Cache的時(shí)候要多加一個(gè)屬性preloadSecondTime來存儲(chǔ)這個(gè)刷新時(shí)間乐尊。并在getMissingCache方法創(chuàng)建Cache對象的時(shí)候指定該值戚丸。
CustomizedRedisCache部分源碼:
/**
* 緩存主動(dòng)在失效前強(qiáng)制刷新緩存的時(shí)間
* 單位:秒
*/
private long preloadSecondTime = 0;
// 重寫后的構(gòu)造方法
public CustomizedRedisCache(String name, byte[] prefix, RedisOperations<? extends Object, ? extends Object> redisOperations, long expiration, long preloadSecondTime) {
super(name, prefix, redisOperations, expiration);
this.redisOperations = redisOperations;
// 指定自動(dòng)刷新時(shí)間
this.preloadSecondTime = preloadSecondTime;
this.prefix = prefix;
}
// 重寫后的構(gòu)造方法
public CustomizedRedisCache(String name, byte[] prefix, RedisOperations<? extends Object, ? extends Object> redisOperations, long expiration, long preloadSecondTime, boolean allowNullValues) {
super(name, prefix, redisOperations, expiration, allowNullValues);
this.redisOperations = redisOperations;
// 指定自動(dòng)刷新時(shí)間
this.preloadSecondTime = preloadSecondTime;
this.prefix = prefix;
}
那么這個(gè)自動(dòng)刷新時(shí)間有了,怎么來讓他自動(dòng)刷新呢扔嵌?
在調(diào)用Cache的get方法的時(shí)候我們都會(huì)去緩存服務(wù)查詢緩存限府,這個(gè)時(shí)候我們在多查一個(gè)緩存的有效時(shí)間,和我們配置的自動(dòng)刷新時(shí)間對比痢缎,如果緩存的有效時(shí)間小于這個(gè)自動(dòng)刷新時(shí)間我們就去刷新緩存(這里注意一點(diǎn)在高并發(fā)下我們最好只放一個(gè)請求去刷新數(shù)據(jù)胁勺,盡量減少數(shù)據(jù)的壓力,所以在這個(gè)位置加一個(gè)分布式鎖)独旷。所以我們重寫這個(gè)get方法署穗。
CustomizedRedisCache部分源碼:
/**
* 重寫get方法寥裂,獲取到緩存后再次取緩存剩余的時(shí)間,如果時(shí)間小余我們配置的刷新時(shí)間就手動(dòng)刷新緩存案疲。
* 為了不影響get的性能封恰,啟用后臺(tái)線程去完成緩存的刷。
* 并且只放一個(gè)線程去刷新數(shù)據(jù)褐啡。
*
* @param key
* @return
*/
@Override
public ValueWrapper get(final Object key) {
RedisCacheKey cacheKey = getRedisCacheKey(key);
String cacheKeyStr = new String(cacheKey.getKeyBytes());
// 調(diào)用重寫后的get方法
ValueWrapper valueWrapper = this.get(cacheKey);
if (null != valueWrapper) {
// 刷新緩存數(shù)據(jù)
refreshCache(key, cacheKeyStr);
}
return valueWrapper;
}
/**
* 重寫父類的get函數(shù)诺舔。
* 父類的get方法,是先使用exists判斷key是否存在春贸,不存在返回null混萝,存在再到redis緩存中去取值。這樣會(huì)導(dǎo)致并發(fā)問題萍恕,
* 假如有一個(gè)請求調(diào)用了exists函數(shù)判斷key存在逸嘀,但是在下一時(shí)刻這個(gè)緩存過期了,或者被刪掉了允粤。
* 這時(shí)候再去緩存中獲取值的時(shí)候返回的就是null了崭倘。
* 可以先獲取緩存的值,再去判斷key是否存在类垫。
*
* @param cacheKey
* @return
*/
@Override
public RedisCacheElement get(final RedisCacheKey cacheKey) {
Assert.notNull(cacheKey, "CacheKey must not be null!");
// 根據(jù)key獲取緩存值
RedisCacheElement redisCacheElement = new RedisCacheElement(cacheKey, fromStoreValue(lookup(cacheKey)));
// 判斷key是否存在
Boolean exists = (Boolean) redisOperations.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.exists(cacheKey.getKeyBytes());
}
});
if (!exists.booleanValue()) {
return null;
}
return redisCacheElement;
}
/**
* 刷新緩存數(shù)據(jù)
*/
private void refreshCache(Object key, String cacheKeyStr) {
Long ttl = this.redisOperations.getExpire(cacheKeyStr);
if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
// 盡量少的去開啟線程司光,因?yàn)榫€程池是有限的
ThreadTaskHelper.run(new Runnable() {
@Override
public void run() {
// 加一個(gè)分布式鎖,只放一個(gè)請求去刷新緩存
RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
try {
if (redisLock.lock()) {
// 獲取鎖之后再判斷一下過期時(shí)間悉患,看是否需要加載數(shù)據(jù)
Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr);
if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
// 通過獲取代理方法信息重新加載緩存數(shù)據(jù)
CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), key.toString());
}
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock.unlock();
}
}
});
}
}
那么自動(dòng)刷新肯定要掉用方法訪問數(shù)據(jù)庫残家,獲取值后去刷新緩存。這時(shí)我們又怎么能去調(diào)用方法呢售躁?
我們利用java的反射機(jī)制坞淮。所以我們要用一個(gè)容器來存放緩存方法的方法信息,包括對象陪捷,方法名稱回窘,參數(shù)等等。我們創(chuàng)建了CachedInvocation類來存放這些信息市袖,再將這個(gè)類的對象維護(hù)到容器中啡直。
CachedInvocation源碼:
public final class CachedInvocation {
private Object key;
private final Object targetBean;
private final Method targetMethod;
private Object[] arguments;
public CachedInvocation(Object key, Object targetBean, Method targetMethod, Object[] arguments) {
this.key = key;
this.targetBean = targetBean;
this.targetMethod = targetMethod;
if (arguments != null && arguments.length != 0) {
this.arguments = Arrays.copyOf(arguments, arguments.length);
}
}
public Object[] getArguments() {
return arguments;
}
public Object getTargetBean() {
return targetBean;
}
public Method getTargetMethod() {
return targetMethod;
}
public Object getKey() {
return key;
}
/**
* 必須重寫equals和hashCode方法,否則放到set集合里沒法去重
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CachedInvocation that = (CachedInvocation) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}
(方案一)維護(hù)緩存方法信息的容器(在內(nèi)存中建一個(gè)MAP)和刷新緩存的類CacheSupportImpl 關(guān)鍵代碼:
private final String SEPARATOR = "#";
/**
* 記錄緩存執(zhí)行方法信息的容器苍碟。
* 如果有很多無用的緩存數(shù)據(jù)的話酒觅,有可能會(huì)照成內(nèi)存溢出。
*/
private Map<String, Set<CachedInvocation>> cacheToInvocationsMap = new ConcurrentHashMap<>();
@Autowired
private CacheManager cacheManager;
// 刷新緩存
private void refreshCache(CachedInvocation invocation, String cacheName) {
boolean invocationSuccess;
Object computed = null;
try {
// 通過代理調(diào)用方法微峰,并記錄返回值
computed = invoke(invocation);
invocationSuccess = true;
} catch (Exception ex) {
invocationSuccess = false;
}
if (invocationSuccess) {
if (!CollectionUtils.isEmpty(cacheToInvocationsMap.get(cacheName))) {
// 通過cacheManager獲取操作緩存的cache對象
Cache cache = cacheManager.getCache(cacheName);
// 通過Cache對象更新緩存
cache.put(invocation.getKey(), computed);
}
}
}
private Object invoke(CachedInvocation invocation)
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final MethodInvoker invoker = new MethodInvoker();
invoker.setTargetObject(invocation.getTargetBean());
invoker.setArguments(invocation.getArguments());
invoker.setTargetMethod(invocation.getTargetMethod().getName());
invoker.prepare();
return invoker.invoke();
}
// 注冊緩存方法的執(zhí)行類信息
@Override
public void registerInvocation(Object targetBean, Method targetMethod, Object[] arguments,
Set<String> annotatedCacheNames, String cacheKey) {
// 獲取注解上真實(shí)的value值
Collection<String> cacheNames = generateValue(annotatedCacheNames);
// 獲取注解上的key屬性值
Class<?> targetClass = getTargetClass(targetBean);
Collection<? extends Cache> caches = getCache(cacheNames);
Object key = generateKey(caches, cacheKey, targetMethod, arguments, targetBean, targetClass,
CacheOperationExpressionEvaluator.NO_RESULT);
// 新建一個(gè)代理對象(記錄了緩存注解的方法類信息)
final CachedInvocation invocation = new CachedInvocation(key, targetBean, targetMethod, arguments);
for (final String cacheName : cacheNames) {
if (!cacheToInvocationsMap.containsKey(cacheName)) {
cacheToInvocationsMap.put(cacheName, new CopyOnWriteArraySet<>());
}
cacheToInvocationsMap.get(cacheName).add(invocation);
}
}
@Override
public void refreshCache(String cacheName) {
this.refreshCacheByKey(cacheName, null);
}
// 刷新特定key緩存
@Override
public void refreshCacheByKey(String cacheName, String cacheKey) {
// 如果根據(jù)緩存名稱沒有找到代理信息類的set集合就不執(zhí)行刷新操作阐滩。
// 只有等緩存有效時(shí)間過了,再走到切面哪里然后把代理方法信息注冊到這里來县忌。
if (!CollectionUtils.isEmpty(cacheToInvocationsMap.get(cacheName))) {
for (final CachedInvocation invocation : cacheToInvocationsMap.get(cacheName)) {
if (!StringUtils.isBlank(cacheKey) && invocation.getKey().toString().equals(cacheKey)) {
logger.info("緩存:{}-{}掂榔,重新加載數(shù)據(jù)", cacheName, cacheKey.getBytes());
refreshCache(invocation, cacheName);
}
}
}
}
(方案二)維護(hù)緩存方法信息的容器(放到Redis)這個(gè)部分代碼貼出來,直接看源碼症杏。
現(xiàn)在刷新緩存和注冊緩存執(zhí)行方法的信息都有了装获,我們怎么來把這個(gè)執(zhí)行方法信息注冊到容器里面呢?這里還少了觸發(fā)點(diǎn)厉颤。
所以我們還需要一個(gè)切面穴豫,當(dāng)執(zhí)行@Cacheable注解獲取緩存信息的時(shí)候我們還需要注冊執(zhí)行方法的信息,所以我們寫了一個(gè)切面:
/**
* 緩存攔截逼友,用于注冊方法信息
* @author yuhao.wang
*/
@Aspect
@Component
public class CachingAnnotationsAspect {
private static final Logger logger = LoggerFactory.getLogger(CachingAnnotationsAspect.class);
@Autowired
private InvocationRegistry cacheRefreshSupport;
private <T extends Annotation> List<T> getMethodAnnotations(AnnotatedElement ae, Class<T> annotationType) {
List<T> anns = new ArrayList<T>(2);
// look for raw annotation
T ann = ae.getAnnotation(annotationType);
if (ann != null) {
anns.add(ann);
}
// look for meta-annotations
for (Annotation metaAnn : ae.getAnnotations()) {
ann = metaAnn.annotationType().getAnnotation(annotationType);
if (ann != null) {
anns.add(ann);
}
}
return (anns.isEmpty() ? null : anns);
}
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Method method = methodSignature.getMethod();
// The method may be on an interface, but we need attributes from the
// target class. If the target class is null, the method will be
// unchanged.
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
if (targetClass == null && pjp.getTarget() != null) {
targetClass = pjp.getTarget().getClass();
}
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
// If we are dealing with method with generic parameters, find the
// original method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
return specificMethod;
}
@Pointcut("@annotation(org.springframework.cache.annotation.Cacheable)")
public void pointcut() {
}
@Around("pointcut()")
public Object registerInvocation(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = this.getSpecificmethod(joinPoint);
List<Cacheable> annotations = this.getMethodAnnotations(method, Cacheable.class);
Set<String> cacheSet = new HashSet<String>();
String cacheKey = null;
for (Cacheable cacheables : annotations) {
cacheSet.addAll(Arrays.asList(cacheables.value()));
cacheKey = cacheables.key();
}
cacheRefreshSupport.registerInvocation(joinPoint.getTarget(), method, joinPoint.getArgs(), cacheSet, cacheKey);
return joinPoint.proceed();
}
}
注意:一個(gè)緩存名稱(@Cacheable的value屬性)精肃,也只能配置一個(gè)過期時(shí)間,如果配置多個(gè)以第一次配置的為準(zhǔn)帜乞。
至此我們就把完整的設(shè)置過期時(shí)間和刷新緩存都實(shí)現(xiàn)了司抱,當(dāng)然還可能存在一定問題,希望大家多多指教黎烈。
使用這種方式有個(gè)不好的地方习柠,我們破壞了Spring Cache的結(jié)構(gòu),導(dǎo)致我們切換Cache的方式的時(shí)候要改代碼照棋,有很大的依賴性资溃。
下一篇我將對 redisCacheManager.setExpires()方法進(jìn)行擴(kuò)展來實(shí)現(xiàn)過期時(shí)間和自動(dòng)刷新,進(jìn)而不會(huì)去破壞Spring Cache的原有結(jié)構(gòu)烈炭,切換緩存就不會(huì)有問題了溶锭。
代碼結(jié)構(gòu)圖:
源碼地址:
https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases
spring-boot-student-cache-redis 工程
參考:
- http://www.cnblogs.com/ASPNET2008/p/6511500.html
- http://www.cnblogs.com/bobsha/p/6507165.html
- http://m.blog.csdn.net/whatlookingfor/article/details/51833378
- http://hbxflihua.iteye.com/blog/2354414
為監(jiān)控而生的多級緩存框架 layering-cache這是我開源的一個(gè)多級緩存框架的實(shí)現(xiàn),如果有興趣可以看一下