Spring Boot緩存實(shí)戰(zhàn) Redis 設(shè)置有效時(shí)間和自動(dòng)刷新緩存厂抖,時(shí)間支持在配置文件中配置

問題描述

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);

    ...
}

請求步驟

  1. 請求進(jìn)來妒御,在方法上面掃描@Cacheable注解,那么會(huì)觸發(fā)org.springframework.cache.interceptor.CacheInterceptor緩存的攔截器镇饺。
  2. 然后會(huì)調(diào)用CacheManager的getCache方法携丁,獲取Cache,如果沒有(第一次訪問)就新建一Cache并返回兰怠。
  3. 根據(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)圖:


image

源碼地址:
https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

spring-boot-student-cache-redis 工程

參考:

為監(jiān)控而生的多級緩存框架 layering-cache這是我開源的一個(gè)多級緩存框架的實(shí)現(xiàn),如果有興趣可以看一下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末符隙,一起剝皮案震驚了整個(gè)濱河市趴捅,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌膏执,老刑警劉巖驻售,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異更米,居然都是意外死亡欺栗,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進(jìn)店門征峦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來迟几,“玉大人,你說我怎么就攤上這事栏笆±嗳” “怎么了?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵蛉加,是天一觀的道長蚜枢。 經(jīng)常有香客問我缸逃,道長,這世上最難降的妖魔是什么厂抽? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任需频,我火速辦了婚禮,結(jié)果婚禮上筷凤,老公的妹妹穿的比我還像新娘昭殉。我一直安慰自己,他們只是感情好藐守,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布挪丢。 她就那樣靜靜地躺著,像睡著了一般卢厂。 火紅的嫁衣襯著肌膚如雪乾蓬。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天足淆,我揣著相機(jī)與錄音巢块,去河邊找鬼。 笑死巧号,一個(gè)胖子當(dāng)著我的面吹牛族奢,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播丹鸿,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼越走,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了靠欢?” 一聲冷哼從身側(cè)響起廊敌,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎门怪,沒想到半個(gè)月后骡澈,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡掷空,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年肋殴,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坦弟。...
    茶點(diǎn)故事閱讀 40,090評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡护锤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出酿傍,到底是詐尸還是另有隱情烙懦,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布赤炒,位于F島的核電站氯析,受9級特大地震影響亏较,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜魄鸦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一宴杀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧拾因,春花似錦、人聲如沸旷余。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽正卧。三九已至蠢熄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間炉旷,已是汗流浹背签孔。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留窘行,地道東北人饥追。 一個(gè)月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像罐盔,于是被迫代替她去往敵國和親但绕。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,163評論 25 707
  • 一惶看、簡介 Ehcache是一個(gè)用Java實(shí)現(xiàn)的使用簡單捏顺,高速,實(shí)現(xiàn)線程安全的緩存管理類庫纬黎,ehcache提供了用內(nèi)...
    小程故事多閱讀 43,862評論 9 59
  • 理論總結(jié) 它要解決什么樣的問題幅骄? 數(shù)據(jù)的訪問、存取本今、計(jì)算太慢拆座、太不穩(wěn)定、太消耗資源诈泼,同時(shí)懂拾,這樣的操作存在重復(fù)性。因...
    jiangmo閱讀 2,853評論 0 11
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理铐达,服務(wù)發(fā)現(xiàn)岖赋,斷路器,智...
    卡卡羅2017閱讀 134,659評論 18 139
  • 《人生最美不是風(fēng)景》 文/白傳英 曾想走遍世界各地 把身影留在身后 也想吃盡山珍海味 不白活這一回 為了...
    白清風(fēng)閱讀 122評論 0 0