Map缓存适配成带生存期的缓存

来源:互联网 发布:圣女贞德 知乎 编辑:程序博客网 时间:2024/04/29 22:36

前段时间,做了个数据缓存,很简单你,使用一个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>();
    };