weixin4j-base:获取cache时加锁处理(via 风车车)
This commit is contained in:
parent
42a3fc357e
commit
6c00f26e13
@ -735,4 +735,6 @@
|
|||||||
|
|
||||||
* 2016-07-22
|
* 2016-07-22
|
||||||
|
|
||||||
+ weixin4j-base:主要调整退款相关类与官网一致
|
+ weixin4j-base:主要调整退款相关类与官网一致
|
||||||
|
|
||||||
|
+ weixin4j-base:获取cache时加锁处理(via 风车车)
|
||||||
@ -1,5 +1,8 @@
|
|||||||
package com.foxinmy.weixin4j.cache;
|
package com.foxinmy.weixin4j.cache;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
import com.foxinmy.weixin4j.exception.WeixinException;
|
import com.foxinmy.weixin4j.exception.WeixinException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -14,6 +17,7 @@ import com.foxinmy.weixin4j.exception.WeixinException;
|
|||||||
public class CacheManager<T extends Cacheable> {
|
public class CacheManager<T extends Cacheable> {
|
||||||
protected final CacheCreator<T> cacheCreator;
|
protected final CacheCreator<T> cacheCreator;
|
||||||
protected final CacheStorager<T> cacheStorager;
|
protected final CacheStorager<T> cacheStorager;
|
||||||
|
private final ReentrantLock lock = new ReentrantLock();
|
||||||
|
|
||||||
public CacheManager(CacheCreator<T> cacheCreator,
|
public CacheManager(CacheCreator<T> cacheCreator,
|
||||||
CacheStorager<T> cacheStorager) {
|
CacheStorager<T> cacheStorager) {
|
||||||
@ -30,9 +34,20 @@ public class CacheManager<T extends Cacheable> {
|
|||||||
public T getCache() throws WeixinException {
|
public T getCache() throws WeixinException {
|
||||||
String cacheKey = cacheCreator.key();
|
String cacheKey = cacheCreator.key();
|
||||||
T cache = cacheStorager.lookup(cacheKey);
|
T cache = cacheStorager.lookup(cacheKey);
|
||||||
if (cache == null) {
|
try {
|
||||||
cache = cacheCreator.create();
|
if (cache == null && lock.tryLock(3, TimeUnit.SECONDS)) {
|
||||||
cacheStorager.caching(cacheKey, cache);
|
try {
|
||||||
|
cache = cacheStorager.lookup(cacheKey);
|
||||||
|
if (cache == null) {
|
||||||
|
cache = cacheCreator.create();
|
||||||
|
cacheStorager.caching(cacheKey, cache);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new WeixinException("get cache error on lock", e);
|
||||||
}
|
}
|
||||||
return cache;
|
return cache;
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user