CacheManager.java

  1. package com.foxinmy.weixin4j.cache;

  2. import java.util.concurrent.TimeUnit;
  3. import java.util.concurrent.locks.ReentrantLock;

  4. import com.foxinmy.weixin4j.exception.WeixinException;

  5. /**
  6.  * 缓存管理类
  7.  *
  8.  * @className CacheManager
  9.  * @author jinyu(foxinmy@gmail.com)
  10.  * @date 2016年5月27日
  11.  * @since JDK 1.7
  12.  * @see
  13.  */
  14. public class CacheManager<T extends Cacheable> {
  15.     protected final CacheCreator<T> cacheCreator;
  16.     protected final CacheStorager<T> cacheStorager;
  17.     private final ReentrantLock lock = new ReentrantLock();

  18.     public CacheManager(CacheCreator<T> cacheCreator, CacheStorager<T> cacheStorager) {
  19.         this.cacheCreator = cacheCreator;
  20.         this.cacheStorager = cacheStorager;
  21.     }

  22.     /**
  23.      * 获取缓存对象
  24.      *
  25.      * @return 缓存对象
  26.      * @throws WeixinException
  27.      */
  28.     public T getCache() throws WeixinException {
  29.         String cacheKey = cacheCreator.key();
  30.         T cache = cacheStorager.lookup(cacheKey);
  31.         try {
  32.             if (cache == null && lock.tryLock(3, TimeUnit.SECONDS)) {
  33.                 try {
  34.                     cache = cacheStorager.lookup(cacheKey);
  35.                     if (cache == null) {
  36.                         cache = cacheCreator.create();
  37.                         cacheStorager.caching(cacheKey, cache);
  38.                     }
  39.                 } finally {
  40.                     lock.unlock();
  41.                 }
  42.             }
  43.         } catch (InterruptedException e) {
  44.             throw new WeixinException("get cache error on lock", e);
  45.         }
  46.         return cache;
  47.     }

  48.     /**
  49.      * 刷新缓存对象
  50.      *
  51.      * @return 缓存对象
  52.      * @throws WeixinException
  53.      */
  54.     public T refreshCache() throws WeixinException {
  55.         String cacheKey = cacheCreator.key();
  56.         T cache = cacheCreator.create();
  57.         cacheStorager.caching(cacheKey, cache);
  58.         return cache;
  59.     }

  60.     /**
  61.      * 移除缓存
  62.      *
  63.      * @return 被移除的缓存对象
  64.      */
  65.     public T evictCache() {
  66.         String cacheKey = cacheCreator.key();
  67.         return cacheStorager.evict(cacheKey);
  68.     }

  69.     /**
  70.      * 清除所有的缓存(<font color="red">请慎重</font>)
  71.      */
  72.     public void clearCache() {
  73.         cacheStorager.clear();
  74.     }
  75. }