使用spring-data-redis做緩存


     說到緩存,首先肯定是spring-cache了.

     spring-cache使用一個CacheManager來進行管理緩存,為了使用我們的redis作為緩存源,需要向spring注冊一個CacheManager

@Bean(name = "redisCacheManager")
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) throws IOException {

        RedisCacheManager manage = new RedisCacheManager(redisTemplate);
        log.info("redis 默認過期時間 {} 秒", redisDefaultExpiration);
     //這里可以設置一個默認的過期時間 manage.setDefaultExpiration(redisDefaultExpiration); manage.setExpires(
this.loadFromConfig()); return manage; }

具體redisTemplate請參考上一篇:http://www.cnblogs.com/lic309/p/5056248.html

  我們都知道spring-cache是不能夠在注解上配置過期時間的,那么如何自己定義每個緩存的過期時間呢。

  首先有個方法叫做:setDefaultExpiration,這里可以設置一個默認的過期時間。

  其次還有一個setExpires方法:

  

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

    其接受一個Map類型,key為緩存的value,value為long

  比如在Map中put一個

  

map.put("AccountCache",1000L);

   那么所有的AccountCache的緩存過期時間為1000秒

 

@Cacheable(value = "AccountCache", key = "T(com.morequ.usercenter.util.ConfigurationPropertys).ACCOUNTFINDBYID+#id")
    public Account findById(long id) {
...
}

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM