自定义的缓存方法,这种缓存方法只在第一次访问时慢
在action中使用下面方法调用缓存:
channel = channelManager.preCacheGetChannel(style, "INDEX","index");
ChannelManagerImpl:
private static final long MAX_FRESH_TIME = 60 * 1000;//1min
private static final int FIXED_CACHE_SIZE = 1000; //缓存的大小
public Channel preCacheGetChannel(String style, String channelType,
String cacheKey) {
//用三个属性拼出key值
String key = new StringBuilder()
.append("style:" + style)
.append(";channelType:" + channelType)
.append(";cacheKey:" + cacheKey)
.toString();
//获取缓存后的channel
PreCacheChannel pchannel = PRE_CACHE_MAP.get(key);
//如果没有缓存则新建一个缓存
if(pchannel == null) {
//获取真正的channel
Channel channel = getChannel(style, channelType);
//将channel的所有属性放到copy一个新的channel中
Channel copy = copyOfChannel(channel);
pchannel= new PreCacheChannel(MAX_FRESH_TIME);
pchannel.setChannel(copy);
pchannel.setLastRefreshTime(System.currentTimeMillis());
pchannel.setOnLoading(false);
PRE_CACHE_MAP.put(key, pchannel);
} else if (!pchannel.isFresh()) {
preLoading(style, channelType, key, pchannel);
}
return pchannel.getChannel();
}
private static final Map<String, PreCacheChannel> PRE_CACHE_MAP = Collections.synchronizedMap( //获取一个线程安全的map
new LinkedHashMap<String, PreCacheChannel>(FIXED_CACHE_SIZE, 1.1f, true) {
@Override
protected boolean removeEldestEntry(
Map.Entry<String, PreCacheChannel> eldest) {
if (this.size() >= FIXED_CACHE_SIZE) {
return true;
}
return false;
}
});
class PreCacheChannel {
Channel channel;
long lastRefreshTime;
volatile boolean onLoading;
long maxFreshTime;
/**
* @param maxFreshTime
*/
public PreCacheChannel(long maxFreshTime) {
super();
this.maxFreshTime = maxFreshTime;
}
/**
* 默认构造函数
*/
public PreCacheChannel() {
super();
}
/**
*是否超过缓存时间
*/
public boolean isFresh() {
return System.currentTimeMillis() - lastRefreshTime < maxFreshTime;
}
。。。。。。。。。//getter and setter
}