• 缓存工具类(使用ConcurrentMap集合实现)


    public class Cache {
    
        static ConcurrentMap<String, Cache> datas = new  ConcurrentHashMap<String, Cache>();//缓存集合
        static long pMaxTime=1000*60*5;//最大缓存时间(毫秒)
        
        private Cache(String key,Object data,long maxTime){
            this.key=key;
            this.time=System.currentTimeMillis();
            this.data=data;
            this.maxTime=maxTime;
        }
        
        String key;//键值
        long time;//缓存时间
        long maxTime;//最大缓存时间(毫秒)
        Object data=null;
        
        //判断时间是否超时
        public boolean checkTimeIn(){
            return System.currentTimeMillis()-time<maxTime;
            //return false;
        }
        
        //获取缓存
        static public Object getData(String key){
            Cache c = datas.get(key);
            if(c==null || !c.checkTimeIn())
                return null;
            else
                return c.data;
        }
        
        //设置缓存
        static public void setData(String key,Object data){
            setData(key,data,pMaxTime);
        }
        
        //设置缓存
        static public void setData(String key,Object data,long maxTime){
            datas.remove(key);
            datas.put(key, new Cache(key,data,maxTime));
        }
        
        //移除指定key的缓存
        static public void removeData(String key){
            datas.remove(key);
        }
        
        //清除超时缓存
        static public void removeOutTimeData(){
            for(Cache c : datas.values()){
                if(!c.checkTimeIn())
                    datas.remove(c.key);
            }
        }
        
        //当前数量
        static public int size(){
            return datas.size();
        }
    }
    View Code

      注:使用此类进行公共数据缓存,最好做个定时器清除一下超时数据(直接调用此方法Cache.removeOutTimeData();)。

  • 相关阅读:
    解决javaScript在不同时区new Date()显示值不同问题
    页面返回上一页浏览位置
    如何disabled禁用所有表单input输入框元素
    js根据json数组多个字段排序
    No identifier specified for entity
    Android resource compilation failed
    android 系统dialog的应用
    android消息处理源码分析
    Linux下常用命令
    ContentProvider和ContentResolver的使用
  • 原文地址:https://www.cnblogs.com/bl123/p/13720328.html
Copyright © 2020-2023  润新知