View Javadoc
1   package com.foxinmy.weixin4j.cache;
2   
3   import java.util.concurrent.TimeUnit;
4   import java.util.concurrent.locks.ReentrantLock;
5   
6   import com.foxinmy.weixin4j.exception.WeixinException;
7   
8   /**
9    * 缓存管理类
10   *
11   * @className CacheManager
12   * @author jinyu(foxinmy@gmail.com)
13   * @date 2016年5月27日
14   * @since JDK 1.7
15   * @see
16   */
17  public class CacheManager<T extends Cacheable> {
18      protected final CacheCreator<T> cacheCreator;
19      protected final CacheStorager<T> cacheStorager;
20      private final ReentrantLock lock = new ReentrantLock();
21  
22      public CacheManager(CacheCreator<T> cacheCreator, CacheStorager<T> cacheStorager) {
23          this.cacheCreator = cacheCreator;
24          this.cacheStorager = cacheStorager;
25      }
26  
27      /**
28       * 获取缓存对象
29       *
30       * @return 缓存对象
31       * @throws WeixinException
32       */
33      public T getCache() throws WeixinException {
34          String cacheKey = cacheCreator.key();
35          T cache = cacheStorager.lookup(cacheKey);
36          try {
37              if (cache == null && lock.tryLock(3, TimeUnit.SECONDS)) {
38                  try {
39                      cache = cacheStorager.lookup(cacheKey);
40                      if (cache == null) {
41                          cache = cacheCreator.create();
42                          cacheStorager.caching(cacheKey, cache);
43                      }
44                  } finally {
45                      lock.unlock();
46                  }
47              }
48          } catch (InterruptedException e) {
49              throw new WeixinException("get cache error on lock", e);
50          }
51          return cache;
52      }
53  
54      /**
55       * 刷新缓存对象
56       *
57       * @return 缓存对象
58       * @throws WeixinException
59       */
60      public T refreshCache() throws WeixinException {
61          String cacheKey = cacheCreator.key();
62          T cache = cacheCreator.create();
63          cacheStorager.caching(cacheKey, cache);
64          return cache;
65      }
66  
67      /**
68       * 移除缓存
69       *
70       * @return 被移除的缓存对象
71       */
72      public T evictCache() {
73          String cacheKey = cacheCreator.key();
74          return cacheStorager.evict(cacheKey);
75      }
76  
77      /**
78       * 清除所有的缓存(<font color="red">请慎重</font>)
79       */
80      public void clearCache() {
81          cacheStorager.clear();
82      }
83  }