1. 程式人生 > >配置redis快取失效時間

配置redis快取失效時間

最近想利用redis快取做一個簡陋版的類似騰訊新聞這樣的檢視新聞的網頁。用了快取以後,新增新聞快取沒有更新,想使用快取的失效時間做到資料庫快取一致性。剛開始做的時候認為使用@CachePut註解會起到更新快取的作用,設定了cacheName和key都和查詢方法中的@Cacheable中的key和cacheName的一樣,然而並沒有成功,反而是被替換了,想想hashMap就能理解這個問題了。

如何設定,通過RedisCacheManage,看名字就知道應該通過它來設定
RedisCacheManage原始碼簡單介紹

1.成員變數:

private final Log logger;
private final RedisOperations redisOperations;
private boolean usePrefix;
private RedisCachePrefix cachePrefix;
private boolean loadRemoteCachesOnStartup;
private boolean dynamic;
private long defaultExpiration;
private Map<String, Long> expires;
private Set<String> configuredCacheNames;
private final boolean cacheNullValues;

我們應該重點關注的是defaultExpiration和Map< String, Long> expires,只有這兩個元素是和快取失效時間有關的

2.建構函式

public RedisCacheManager(RedisOperations redisOperations) {
        this(redisOperations, Collections.emptyList());
    }

public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames) {
    this(redisOperations, cacheNames, false);
}

public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames, boolean cacheNullValues) {
    this.logger = LogFactory.getLog(RedisCacheManager.class);
    this.usePrefix = false;
    this.cachePrefix = new DefaultRedisCachePrefix();
    this.loadRemoteCachesOnStartup = false;
    this.dynamic = true;
    this.defaultExpiration = 0L;
    this.expires = null;
    this.redisOperations = redisOperations;
    this.cacheNullValues = cacheNullValues;
    this.setCacheNames(cacheNames);
}

建構函式依次呼叫,第一個建構函式呼叫第二個建構函式,第二個建構函式呼叫第三個建構函式。我們在使用的時候都是用的第一個建構函式,傳遞進一個redisTemplate。在第三個建構函式中defaultExpiration = 0L,過期時間為0,表示快取用不失效,expires = null表示沒有為任何快取設定快取失效時間

3.設定快取失效的方法

public void setExpires(Map<String, Long> expires) {
        this.expires = expires != null?new ConcurrentHashMap(expires):null;
    }

注意:傳入的引數為Map型別的
如果傳入的引數不為null。則將該值傳遞給expires,並且通過ConcurrentHashMap(expires)包裝了一下,保證是執行緒安全的。

4.用到expires引數的方法

protected long computeExpiration(String name) {
Long expiration = null;
if(this.expires != null) {
expiration = (Long)this.expires.get(name);
}

    return expiration != null?expiration.longValue():this.defaultExpiration;
}

通過get方法獲得對應快取區域的快取失效時間。如果沒有設定快取失效時間,則預設永遠不失效

5.配置快取失效時間
在配置redis的配置檔案中進行修改,我用的是java配置檔案

     /**
     * redis快取管理器
     * */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        Map<String, Long> expires = new HashMap<String, Long>();
        expires.put("news", 60L);
        redisCacheManager.setExpires(expires);
        return redisCacheManager;
    }

時間是以秒作為單位的,Map中對應的鍵值對為快取名和對應的快取失效時間