缓存工具类(使用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();)。

原文地址:https://www.cnblogs.com/bl123/p/13720328.html