Spring Boot緩存實戰 Redis 設置有效時間和自動刷新緩存,時間支持在配置文件中配置

問題描述

Spring Cache提供的@Cacheable注解不支持配置過期時間,還有緩存的自動刷新。
我們可以通過配置CacheManneg來配置默認的過期時間和針對每個緩存容器(value)單獨配置過期時間,但是總是感覺不太靈活。下面是一個示例:

@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;
}

我們想在注解上直接配置過期時間和自動刷新時間,就像這樣:

@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() + "數據做了緩存");
    return p;
}

value屬性上用#號隔開,第一個是原始的緩存容器名稱,第二個是緩存的有效時間,第三個是緩存的自動刷新時間,單位都是秒。

緩存的有效時間和自動刷新時間支持SpEl表達式,支持在配置文件中配置,如:

@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() + "數據做了緩存");
    return p;
}

解決思路

查看源碼你會發現緩存最頂級的接口就是CacheManager和Cache接口。

CacheManager說明

CacheManager功能其實很簡單就是管理cache,接口只有兩個方法,根據容器名稱獲取一個Cache。還有就是返回所有的緩存名稱。

public interface CacheManager {

    /**
     * 根據名稱獲取一個Cache(在實現類里面是如果有這個Cache就返回,沒有就新建一個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);

    /**
     * 返回一個緩存名稱的集合
     * @return the names of all caches known by the cache manager
     */
    Collection<String> getCacheNames();

}

Cache說明

Cache接口主要是操作緩存的。get根據緩存key從緩存服務器獲取緩存中的值,put根據緩存key將數據放到緩存服務器,evict根據key刪除緩存中的數據。

public interface Cache {

    ValueWrapper get(Object key);

    void put(Object key, Object value);

    void evict(Object key);

    ...
}

請求步驟

  1. 請求進來,在方法上面掃描@Cacheable注解,那么會觸發org.springframework.cache.interceptor.CacheInterceptor緩存的攔截器。
  2. 然后會調用CacheManager的getCache方法,獲取Cache,如果沒有(第一次訪問)就新建一Cache并返回。
  3. 根據獲取到的Cache去調用get方法獲取緩存中的值。RedisCache這里有個bug,源碼是先判斷key是否存在,再去緩存獲取值,在高并發下有bug。

代碼分析

在最上面我們說了Spring Cache可以通過配置CacheManager來配置過期時間。那么這個過期時間是在哪里用的呢?設置默認的時間setDefaultExpiration,根據特定名稱設置有效時間setExpires,獲取一個緩存名稱(value屬性)的有效時間computeExpiration,真正使用有效時間是在createCache方法里面,而這個方法是在父類的getCache方法調用。通過RedisCacheManager源碼我們看到:

// 設置默認的時間
public void setDefaultExpiration(long defaultExpireTime) {
    this.defaultExpiration = defaultExpireTime;
}

// 根據特定名稱設置有效時間
public void setExpires(Map<String, Long> expires) {
    this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null);
}
// 獲取一個key的有效時間
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) {
    // 調用了上面的方法獲取緩存名稱的有效時間
    long expiration = computeExpiration(cacheName);
    // 創建了Cache對象,并使用了這個有效時間
    return new RedisCache(cacheName, (usePrefix ? cachePrefix.prefix(cacheName) : null), redisOperations, expiration,
            cacheNullValues);
}

// 重寫父類的getMissingCache。去創建Cache
@Override
protected Cache getMissingCache(String name) {
    return this.dynamic ? createCache(name) : null;
}

AbstractCacheManager父類源碼:

// 根據名稱獲取Cache如果沒有調用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調用該方法,這個方法默認返回值NULL由子類自己實現。上面的就是子類自己實現的方法
                cache = getMissingCache(name);
                if (cache != null) {
                    cache = decorateCache(cache);
                    this.cacheMap.put(name, cache);
                    updateCacheNames(name);
                }
            }
            return cache;
        }
    }
}

由此這個有效時間的設置關鍵就是在getCache方法上,這里的name參數就是我們注解上的value屬性。所以在這里解析這個特定格式的名稱我就可以拿到配置的過期時間和刷新時間。getMissingCache方法里面在新建緩存的時候將這個過期時間設置進去,生成的Cache對象操作緩存的時候就會帶上我們的配置的過期時間,然后過期就生效了。解析SpEL表達式獲取配置文件中的時間也在也一步完成。

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緩存管理器
 * 支持方法上配置過期時間
 * 支持熱加載緩存:緩存即將過期時主動刷新緩存
 *
 * @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";

    /**
     * 緩存參數的分隔符
     * 數組元素0=緩存的名稱
     * 數組元素1=緩存過期時間TTL
     * 數組元素2=緩存在多少秒開始主動失效來強制刷新
     */
    private static final String SEPARATOR = "#";

    /**
     * SpEL標示符
     */
    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;
        }

        // 有效時間,初始化獲取默認的有效時間
        Long expirationSecondTime = getExpirationSecondTime(cacheName, cacheParams);
        // 自動刷新時間,默認是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);
        }

    }

    /**
     * 獲取過期時間
     *
     * @return
     */
    private long getExpirationSecondTime(String cacheName, String[] cacheParams) {
        // 有效時間,初始化獲取默認的有效時間
        Long expirationSecondTime = this.computeExpiration(cacheName);

        // 設置key有效時間
        if (cacheParams.length > 1) {
            String expirationStr = cacheParams[1];
            if (!StringUtils.isEmpty(expirationStr)) {
                // 支持配置過期時間使用EL表達式讀取配置文件時間
                if (expirationStr.contains(MARK)) {
                    expirationStr = beanFactory.resolveEmbeddedValue(expirationStr);
                }
                expirationSecondTime = Long.parseLong(expirationStr);
            }
        }

        return expirationSecondTime;
    }

    /**
     * 獲取自動刷新時間
     *
     * @return
     */
    private long getExpirationSecondTime(String[] cacheParams) {
        // 自動刷新時間,默認是0
        Long preloadSecondTime = 0L;
        // 設置自動刷新時間
        if (cacheParams.length > 2) {
            String preloadStr = cacheParams[2];
            if (!StringUtils.isEmpty(preloadStr)) {
                // 支持配置刷新時間使用EL表達式讀取配置文件時間
                if (preloadStr.contains(MARK)) {
                    preloadStr = beanFactory.resolveEmbeddedValue(preloadStr);
                }
                preloadSecondTime = Long.parseLong(preloadStr);
            }
        }
        return preloadSecondTime;
    }

    /**
     * 重寫父類的getCache方法,真假了三個參數
     *
     * @param cacheName            緩存名稱
     * @param expirationSecondTime 過期時間
     * @param preloadSecondTime    自動刷新時間
     * @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) {
                    // 調用我們自己的getMissingCache方法創建自己的cache
                    cache = getMissingCache(cacheName, expirationSecondTime, preloadSecondTime);
                    if (cache != null) {
                        cache = decorateCache(cache);
                        cacheMap.put(cacheName, cache);

                        // 反射去執行父類的updateCacheNames(cacheName)方法
                        Class<?>[] parameterTypes = {String.class};
                        Object[] parameters = {cacheName};
                        ReflectionUtils.invokeMethod(getInstance(), SUPER_METHOD_UPDATECACHENAMES, parameterTypes, parameters);
                    }
                }
                return cache;
            }
        }
    }

    /**
     * 創建緩存
     *
     * @param cacheName            緩存名稱
     * @param expirationSecondTime 過期時間
     * @param preloadSecondTime    制動刷新時間
     * @return
     */
    public CustomizedRedisCache getMissingCache(String cacheName, long expirationSecondTime, long preloadSecondTime) {

        logger.info("緩存 cacheName:{},過期時間:{}, 自動刷新時間:{}", 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;
    }
}

那自動刷新時間呢?

在RedisCache的屬性里面沒有刷新時間,所以我們繼承該類重寫我們自己的Cache的時候要多加一個屬性preloadSecondTime來存儲這個刷新時間。并在getMissingCache方法創建Cache對象的時候指定該值。

CustomizedRedisCache部分源碼:

/**
 * 緩存主動在失效前強制刷新緩存的時間
 * 單位:秒
 */
private long preloadSecondTime = 0;

// 重寫后的構造方法
public CustomizedRedisCache(String name, byte[] prefix, RedisOperations<? extends Object, ? extends Object> redisOperations, long expiration, long preloadSecondTime) {
    super(name, prefix, redisOperations, expiration);
    this.redisOperations = redisOperations;
    // 指定自動刷新時間
    this.preloadSecondTime = preloadSecondTime;
    this.prefix = prefix;
}

// 重寫后的構造方法
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;
    // 指定自動刷新時間
    this.preloadSecondTime = preloadSecondTime;
    this.prefix = prefix;
}

那么這個自動刷新時間有了,怎么來讓他自動刷新呢?

在調用Cache的get方法的時候我們都會去緩存服務查詢緩存,這個時候我們在多查一個緩存的有效時間,和我們配置的自動刷新時間對比,如果緩存的有效時間小于這個自動刷新時間我們就去刷新緩存(這里注意一點在高并發下我們最好只放一個請求去刷新數據,盡量減少數據的壓力,所以在這個位置加一個分布式鎖)。所以我們重寫這個get方法。

CustomizedRedisCache部分源碼:

/**
 * 重寫get方法,獲取到緩存后再次取緩存剩余的時間,如果時間小余我們配置的刷新時間就手動刷新緩存。
 * 為了不影響get的性能,啟用后臺線程去完成緩存的刷。
 * 并且只放一個線程去刷新數據。
 *
 * @param key
 * @return
 */
@Override
public ValueWrapper get(final Object key) {
    RedisCacheKey cacheKey = getRedisCacheKey(key);
    String cacheKeyStr = new String(cacheKey.getKeyBytes());
    // 調用重寫后的get方法
    ValueWrapper valueWrapper = this.get(cacheKey);

    if (null != valueWrapper) {
        // 刷新緩存數據
        refreshCache(key, cacheKeyStr);
    }
    return valueWrapper;
}

/**
 * 重寫父類的get函數。
 * 父類的get方法,是先使用exists判斷key是否存在,不存在返回null,存在再到redis緩存中去取值。這樣會導致并發問題,
 * 假如有一個請求調用了exists函數判斷key存在,但是在下一時刻這個緩存過期了,或者被刪掉了。
 * 這時候再去緩存中獲取值的時候返回的就是null了。
 * 可以先獲取緩存的值,再去判斷key是否存在。
 *
 * @param cacheKey
 * @return
 */
@Override
public RedisCacheElement get(final RedisCacheKey cacheKey) {

    Assert.notNull(cacheKey, "CacheKey must not be null!");

    // 根據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;
}

/**
 * 刷新緩存數據
 */
private void refreshCache(Object key, String cacheKeyStr) {
    Long ttl = this.redisOperations.getExpire(cacheKeyStr);
    if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
        // 盡量少的去開啟線程,因為線程池是有限的
        ThreadTaskHelper.run(new Runnable() {
            @Override
            public void run() {
                // 加一個分布式鎖,只放一個請求去刷新緩存
                RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
                try {
                    if (redisLock.lock()) {
                        // 獲取鎖之后再判斷一下過期時間,看是否需要加載數據
                        Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr);
                        if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
                            // 通過獲取代理方法信息重新加載緩存數據
                            CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), key.toString());
                        }
                    }
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                } finally {
                    redisLock.unlock();
                }
            }
        });
    }
}

那么自動刷新肯定要掉用方法訪問數據庫,獲取值后去刷新緩存。這時我們又怎么能去調用方法呢?

我們利用java的反射機制。所以我們要用一個容器來存放緩存方法的方法信息,包括對象,方法名稱,參數等等。我們創建了CachedInvocation類來存放這些信息,再將這個類的對象維護到容器中。

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

(方案一)維護緩存方法信息的容器(在內存中建一個MAP)和刷新緩存的類CacheSupportImpl 關鍵代碼:

private final String SEPARATOR = "#";

/**
 * 記錄緩存執行方法信息的容器。
 * 如果有很多無用的緩存數據的話,有可能會照成內存溢出。
 */
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 {
        // 通過代理調用方法,并記錄返回值
        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();
}

// 注冊緩存方法的執行類信息
@Override
public void registerInvocation(Object targetBean, Method targetMethod, Object[] arguments,
        Set<String> annotatedCacheNames, String cacheKey) {

    // 獲取注解上真實的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);

    // 新建一個代理對象(記錄了緩存注解的方法類信息)
    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) {
    // 如果根據緩存名稱沒有找到代理信息類的set集合就不執行刷新操作。
    // 只有等緩存有效時間過了,再走到切面哪里然后把代理方法信息注冊到這里來。
    if (!CollectionUtils.isEmpty(cacheToInvocationsMap.get(cacheName))) {
        for (final CachedInvocation invocation : cacheToInvocationsMap.get(cacheName)) {
            if (!StringUtils.isBlank(cacheKey) && invocation.getKey().toString().equals(cacheKey)) {
                logger.info("緩存:{}-{},重新加載數據", cacheName, cacheKey.getBytes());
                refreshCache(invocation, cacheName);
            }
        }
    }
}

(方案二)維護緩存方法信息的容器(放到Redis)這個部分代碼貼出來,直接看源碼。

現在刷新緩存和注冊緩存執行方法的信息都有了,我們怎么來把這個執行方法信息注冊到容器里面呢?這里還少了觸發點。

所以我們還需要一個切面,當執行@Cacheable注解獲取緩存信息的時候我們還需要注冊執行方法的信息,所以我們寫了一個切面:

/**
 * 緩存攔截,用于注冊方法信息
 * @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();

    }
}

注意:一個緩存名稱(@Cacheable的value屬性),也只能配置一個過期時間,如果配置多個以第一次配置的為準。

至此我們就把完整的設置過期時間和刷新緩存都實現了,當然還可能存在一定問題,希望大家多多指教。

使用這種方式有個不好的地方,我們破壞了Spring Cache的結構,導致我們切換Cache的方式的時候要改代碼,有很大的依賴性。

下一篇我將對 redisCacheManager.setExpires()方法進行擴展來實現過期時間和自動刷新,進而不會去破壞Spring Cache的原有結構,切換緩存就不會有問題了。

代碼結構圖:


image

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

spring-boot-student-cache-redis 工程

參考:

為監控而生的多級緩存框架 layering-cache這是我開源的一個多級緩存框架的實現,如果有興趣可以看一下

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,563評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,694評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,672評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,965評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,690評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,019評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,013評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,188評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,718評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,438評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,667評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,149評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,845評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,252評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,590評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,384評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,765評論 25 708
  • 一、簡介 Ehcache是一個用Java實現的使用簡單,高速,實現線程安全的緩存管理類庫,ehcache提供了用內...
    小程故事多閱讀 44,031評論 9 59
  • 理論總結 它要解決什么樣的問題? 數據的訪問、存取、計算太慢、太不穩定、太消耗資源,同時,這樣的操作存在重復性。因...
    jiangmo閱讀 2,886評論 0 11
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,830評論 18 139
  • 《人生最美不是風景》 文/白傳英 曾想走遍世界各地 把身影留在身后 也想吃盡山珍海味 不白活這一回 為了...
    白清風閱讀 123評論 0 0