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
12
13
14
15
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
31
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
58
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
71
72 public T evictCache() {
73 String cacheKey = cacheCreator.key();
74 return cacheStorager.evict(cacheKey);
75 }
76
77
78
79
80 public void clearCache() {
81 cacheStorager.clear();
82 }
83 }