欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2023年05月31日 09:09:40   作者:xiaolyuh123  
這篇文章主要介紹了Spring?Boot緩存實(shí)戰(zhàn)?Redis?設(shè)置有效時(shí)間和自動(dòng)刷新緩存,時(shí)間支持在配置文件中配置,需要的朋友可以參考下

問(wèn)題描述

Spring Cache提供的@Cacheable注解不支持配置過(guò)期時(shí)間,還有緩存的自動(dòng)刷新。
我們可以通過(guò)配置CacheManneg來(lái)配置默認(rèn)的過(guò)期時(shí)間和針對(duì)每個(gè)緩存容器(value)單獨(dú)配置過(guò)期時(shí)間,但是總是感覺(jué)不太靈活。下面是一個(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;
}

我們想在注解上直接配置過(guò)期時(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屬性上用#號(hào)隔開(kāi),第一個(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)緩存最頂級(jí)的接口就是CacheManager和Cache接口。

CacheManager說(shuō)明

CacheManager功能其實(shí)很簡(jiǎn)單就是管理cache,接口只有兩個(gè)方法,根據(jù)容器名稱獲取一個(gè)Cache。還有就是返回所有的緩存名稱。

 
public interface CacheManager {
    /**
     * 根據(jù)名稱獲取一個(gè)Cache(在實(shí)現(xiàn)類里面是如果有這個(gè)Cache就返回,沒(méi)有就新建一個(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說(shuō)明

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

請(qǐng)求步驟

  • 請(qǐng)求進(jìn)來(lái),在方法上面掃描@Cacheable注解,那么會(huì)觸發(fā)org.springframework.cache.interceptor.CacheInterceptor緩存的攔截器。
  • 然后會(huì)調(diào)用CacheManager的getCache方法,獲取Cache,如果沒(méi)有(第一次訪問(wèn))就新建一Cache并返回。
  • 根據(jù)獲取到的Cache去調(diào)用get方法獲取緩存中的值。RedisCache這里有個(gè)bug,源碼是先判斷key是否存在,再去緩存獲取值,在高并發(fā)下有bug。

代碼分析

在最上面我們說(shuō)了Spring Cache可以通過(guò)配置CacheManager來(lái)配置過(guò)期時(shí)間。那么這個(gè)過(guò)期時(shí)間是在哪里用的呢?設(shè)置默認(rèn)的時(shí)間setDefaultExpiration,根據(jù)特定名稱設(shè)置有效時(shí)間setExpires,獲取一個(gè)緩存名稱(value屬性)的有效時(shí)間computeExpiration,真正使用有效時(shí)間是在createCache方法里面,而這個(gè)方法是在父類的getCache方法調(diào)用。通過(guò)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對(duì)象,并使用了這個(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如果沒(méi)有調(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) {
                // 如果沒(méi)找到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è)特定格式的名稱我就可以拿到配置的過(guò)期時(shí)間和刷新時(shí)間。getMissingCache方法里面在新建緩存的時(shí)候?qū)⑦@個(gè)過(guò)期時(shí)間設(shè)置進(jìn)去,生成的Cache對(duì)象操作緩存的時(shí)候就會(huì)帶上我們的配置的過(guò)期時(shí)間,然后過(guò)期就生效了。解析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緩存管理器
 * 支持方法上配置過(guò)期時(shí)間
 * 支持熱加載緩存:緩存即將過(guò)期時(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=緩存過(guò)期時(shí)間TTL
     * 數(shù)組元素2=緩存在多少秒開(kāi)始主動(dòng)失效來(lái)強(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);
        // 通過(guò)反射獲取父類存放緩存的容器對(duì)象
        Object object = ReflectionUtils.getFieldValue(getInstance(), SUPER_FIELD_CACHEMAP);
        if (object != null && object instanceof ConcurrentHashMap) {
            ConcurrentHashMap<String, Cache> cacheMap = (ConcurrentHashMap<String, Cache>) object;
            // 生成Cache對(duì)象,并將其保存到父類的Cache容器中
            return getCache(cacheName, expirationSecondTime, preloadSecondTime, cacheMap);
        } else {
            return super.getCache(cacheName);
        }
    }
    /**
     * 獲取過(guò)期時(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)) {
                // 支持配置過(guò)期時(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 過(guò)期時(shí)間
     * @param preloadSecondTime    自動(dòng)刷新時(shí)間
     * @param cacheMap             通過(guò)反射獲取的父類的cacheMap對(duì)象
     * @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 過(guò)期時(shí)間
     * @param preloadSecondTime    制動(dòng)刷新時(shí)間
     * @return
     */
    public CustomizedRedisCache getMissingCache(String cacheName, long expirationSecondTime, long preloadSecondTime) {
        logger.info("緩存 cacheName:{},過(guò)期時(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的屬性里面沒(méi)有刷新時(shí)間,所以我們繼承該類重寫我們自己的Cache的時(shí)候要多加一個(gè)屬性preloadSecondTime來(lái)存儲(chǔ)這個(gè)刷新時(shí)間。并在getMissingCache方法創(chuàng)建Cache對(duì)象的時(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í)間有了,怎么來(lái)讓他自動(dòng)刷新呢?

在調(diào)用Cache的get方法的時(shí)候我們都會(huì)去緩存服務(wù)查詢緩存,這個(gè)時(shí)候我們?cè)诙嗖橐粋€(gè)緩存的有效時(shí)間,和我們配置的自動(dòng)刷新時(shí)間對(duì)比,如果緩存的有效時(shí)間小于這個(gè)自動(dòng)刷新時(shí)間我們就去刷新緩存(這里注意一點(diǎn)在高并發(fā)下我們最好只放一個(gè)請(qǐng)求去刷新數(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ā)問(wèn)題,
 * 假如有一個(gè)請(qǐng)求調(diào)用了exists函數(shù)判斷key存在,但是在下一時(shí)刻這個(gè)緩存過(guò)期了,或者被刪掉了。
 * 這時(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) {
        // 盡量少的去開(kāi)啟線程,因?yàn)榫€程池是有限的
        ThreadTaskHelper.run(new Runnable() {
            @Override
            public void run() {
                // 加一個(gè)分布式鎖,只放一個(gè)請(qǐng)求去刷新緩存
                RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
                try {
                    if (redisLock.lock()) {
                        // 獲取鎖之后再判斷一下過(guò)期時(shí)間,看是否需要加載數(shù)據(jù)
                        Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr);
                        if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
                            // 通過(guò)獲取代理方法信息重新加載緩存數(shù)據(jù)
                            CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), key.toString());
                        }
                    }
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                } finally {
                    redisLock.unlock();
                }
            }
        });
    }
}

那么自動(dòng)刷新肯定要掉用方法訪問(wèn)數(shù)據(jù)庫(kù),獲取值后去刷新緩存。這時(shí)我們又怎么能去調(diào)用方法呢?

我們利用java的反射機(jī)制。所以我們要用一個(gè)容器來(lái)存放緩存方法的方法信息,包括對(duì)象,方法名稱,參數(shù)等等。我們創(chuàng)建了CachedInvocation類來(lái)存放這些信息,再將這個(gè)類的對(duì)象維護(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集合里沒(méi)法去重
     * @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ù)緩存方法信息的容器和刷新緩存的類CacheSupportImpl 關(guān)鍵代碼:

 
private final String SEPARATOR = "#";
/**
 * 記錄緩存執(zhí)行方法信息的容器。
 * 如果有很多無(wú)用的緩存數(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 {
        // 通過(guò)代理調(diào)用方法,并記錄返回值
        computed = invoke(invocation);
        invocationSuccess = true;
    } catch (Exception ex) {
        invocationSuccess = false;
    }
    if (invocationSuccess) {
        if (!CollectionUtils.isEmpty(cacheToInvocationsMap.get(cacheName))) {
            // 通過(guò)cacheManager獲取操作緩存的cache對(duì)象
            Cache cache = cacheManager.getCache(cacheName);
            // 通過(guò)Cache對(duì)象更新緩存
            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();
}
// 注冊(cè)緩存方法的執(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è)代理對(duì)象(記錄了緩存注解的方法類信息)
    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ù)緩存名稱沒(méi)有找到代理信息類的set集合就不執(zhí)行刷新操作。
    // 只有等緩存有效時(shí)間過(guò)了,再走到切面哪里然后把代理方法信息注冊(cè)到這里來(lái)。
    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);
            }
        }
    }
}

現(xiàn)在刷新緩存和注冊(cè)緩存執(zhí)行方法的信息都有了,我們?cè)趺磥?lái)把這個(gè)執(zhí)行方法信息注冊(cè)到容器里面呢?這里還少了觸發(fā)點(diǎn)。

所以我們還需要一個(gè)切面,當(dāng)執(zhí)行@Cacheable注解獲取緩存信息的時(shí)候我們還需要注冊(cè)執(zhí)行方法的信息,所以我們寫了一個(gè)切面:

 
/**
 * 緩存攔截,用于注冊(cè)方法信息
 * @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è)過(guò)期時(shí)間,如果配置多個(gè)以第一次配置的為準(zhǔn)。

至此我們就把完整的設(shè)置過(guò)期時(shí)間和刷新緩存都實(shí)現(xiàn)了,當(dāng)然還可能存在一定問(wèn)題,希望大家多多指教。

使用這種方式有個(gè)不好的地方,我們破壞了Spring Cache的結(jié)構(gòu),導(dǎo)致我們切換Cache的方式的時(shí)候要改代碼,有很大的依賴性。

下一篇我將對(duì) redisCacheManager.setExpires()方法進(jìn)行擴(kuò)展來(lái)實(shí)現(xiàn)過(guò)期時(shí)間和自動(dòng)刷新,進(jìn)而不會(huì)去破壞Spring Cache的原有結(jié)構(gòu),切換緩存就不會(huì)有問(wèn)題了。

代碼結(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

到此這篇關(guān)于Spring Boot緩存實(shí)戰(zhàn) Redis 設(shè)置有效時(shí)間和自動(dòng)刷新緩存,時(shí)間支持在配置文件中配置的文章就介紹到這了,更多相關(guān)Spring Boot Redis自動(dòng)刷新緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Windows下Java環(huán)境變量配置詳解

    Windows下Java環(huán)境變量配置詳解

    這篇文中給大家介紹的是關(guān)于Windows下JAVA環(huán)境變量JAVA_HOME、CLASSPATH、PATH設(shè)置的相關(guān)資料,文中介紹的還是相對(duì)比較詳細(xì)的,對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-03-03
  • Java中JSON處理工具類使用詳解

    Java中JSON處理工具類使用詳解

    這篇文章主要為大家詳細(xì)介紹了Java中JSON處理工具類的使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Java transient 關(guān)鍵字是干啥的

    Java transient 關(guān)鍵字是干啥的

    這篇文章主要介紹了Java transient 關(guān)鍵字是干啥的,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • @RequestBody注解Ajax post json List集合數(shù)據(jù)請(qǐng)求400/415的處理

    @RequestBody注解Ajax post json List集合數(shù)據(jù)請(qǐng)求400/41

    這篇文章主要介紹了@RequestBody注解Ajax post json List集合數(shù)據(jù)請(qǐng)求400/415的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • jconsole使用介紹(圖文)

    jconsole使用介紹(圖文)

    大家在學(xué)習(xí)java的時(shí)候,難免會(huì)對(duì)jvm進(jìn)行一些深入的了解。推薦大家使用jdk下面的jconsole.exe來(lái)輔助理解jvm的一些概念
    2015-12-12
  • Java實(shí)現(xiàn)AES加密算法的簡(jiǎn)單示例分享

    Java實(shí)現(xiàn)AES加密算法的簡(jiǎn)單示例分享

    這篇文章主要介紹了Java實(shí)現(xiàn)AES加密算法的簡(jiǎn)單示例分享,AES算法是基于對(duì)密碼值的置換和替代,需要的朋友可以參考下
    2016-04-04
  • java字符串常用操作方法(查找、截取、分割)

    java字符串常用操作方法(查找、截取、分割)

    今天小編就為大家分享一篇java字符串常用操作方法(查找、截取、分割),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-07-07
  • 淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理

    淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理

    這篇文章主要介紹了淺談一下SpringCloud中Hystrix服務(wù)熔斷和降級(jí)原理,Hystrix 是 Netflix 的一款開(kāi)源的容錯(cuò)框架,通過(guò)服務(wù)隔離來(lái)避免由于依賴延遲、異常,引起資源耗盡導(dǎo)致系統(tǒng)不可用的解決方案,需要的朋友可以參考下
    2023-05-05
  • ArrayList的自動(dòng)擴(kuò)充機(jī)制實(shí)例解析

    ArrayList的自動(dòng)擴(kuò)充機(jī)制實(shí)例解析

    本文主要介紹了ArrayList的自動(dòng)擴(kuò)充機(jī)制,由一個(gè)題目切入主題,逐步向大家展示了ArrayList的相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • Spring定時(shí)任務(wù)@Scheduled注解(cron表達(dá)式fixedRate?fixedDelay)

    Spring定時(shí)任務(wù)@Scheduled注解(cron表達(dá)式fixedRate?fixedDelay)

    這篇文章主要為大家介紹了Spring定時(shí)任務(wù)@Scheduled注解(cron表達(dá)式fixedRate?fixedDelay)使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11

最新評(píng)論