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

本文介绍了一个将简单Map缓存改造为带有生存期的缓存的方法。通过覆盖`get`和`put`方法,实现了根据预设的生存期判断缓存是否失效的功能。当生存期为0时,缓存永不失效;否则,在超过设定的生存期后,缓存将被移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值