前段时间,做了个数据缓存,很简单你,使用一个Map实现:
Map<String, List> mapCacheList = new Hashtable<String, List>();
现在有个需求,就是设置一个生存期,过去的缓存无效。为了不改动以前的代码,做了以下适配:
public static Map<String, List> mapCacheList = new Hashtable<String, List>(){
@Override
public List get(Object key) {
if(ApplicationParameter.CACHEDELAY == -1) { //缓存被关闭
return null;
}
if(ApplicationParameter.CACHEDELAY == 0) { //永不失效
return super.get(key);
}
Long iStartTick = mapStartTick.get(key);
if(iStartTick != null) {
if(System.currentTimeMillis()-iStartTick > Long.valueOf(ApplicationParameter.CACHEDELAY)*60*1000) {
mapStartTick.remove(key);
remove(key);
return null;
}
return super.get(key);
}
return null;
}
@Override
public List put(String key, List value) {
if(ApplicationParameter.CACHEDELAY == -1) { //缓存被关闭
return value;
}
if(ApplicationParameter.CACHEDELAY == 0) { //永不失效
return super.put(key, value);
}
List lstRet = super.put(key, value);
mapStartTick.put(key, System.currentTimeMillis());
return lstRet;
}
private Map<String, Long> mapStartTick = new HashMap<String, Long>();
};
本文介绍了一个将简单Map缓存改造为带有生存期的缓存的方法。通过覆盖`get`和`put`方法,实现了根据预设的生存期判断缓存是否失效的功能。当生存期为0时,缓存永不失效;否则,在超过设定的生存期后,缓存将被移除。
450

被折叠的 条评论
为什么被折叠?



