Java缓存及过期处理的简单实现「建议收藏」

Java缓存及过期处理的简单实现「建议收藏」/***缓存类实体类*/publicclassCacheEntity<T>{/***要存储的数据*/privateTvalue;/***创建的时间单位ms*/privatelongcreateTime=System.currentTimeMillis();…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

1. 创建缓存实体类

保存需要缓存的数据,缓存创建的时间和缓存的有效期

/** * 缓存类实体类 */
public class CacheEntity<T> { 
   

    /** * 要存储的数据 */
    private T value;

    /** * 创建的时间 单位ms */
    private long createTime = System.currentTimeMillis();

    /** * 缓存的有效时间 单位ms (小于等于0表示永久保存) */
    private long cacheTime;

    public CacheEntity() { 
   
        super();
    }

    public CacheEntity(T value, long cacheTime) { 
   
        this.value = value;
        this.cacheTime = cacheTime;
    }

    public T getValue() { 
   
        return value;
    }

    public void setValue(T value) { 
   
        this.value = value;
    }

    public long getCreateTime() { 
   
        return createTime;
    }

    public void setCreateTime(long createTime) { 
   
        this.createTime = createTime;
    }

    public long getCacheTime() { 
   
        return cacheTime;
    }

    public void setCacheTime(long cacheTime) { 
   
        this.cacheTime = cacheTime;
    }
}

2. 缓存的管理类

主要用户管理缓存数据,对数据的添加,删除。对缓存数据有效性校验,其中创建了一个Timer定时任务,每分钟执行一次缓存清理。

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/** * 缓存管理器 */
public class CacheManager { 
   

    /** * 缓存Map对象 */
    private static ConcurrentHashMap<String,CacheEntity> cacheMap = new ConcurrentHashMap<>();

    /** * 创建定时任务每分钟清理一次缓存 */
    static{ 
   
        Timer timer = new Timer();
        timer.schedule(new TimerTask() { 
   
            @Override
            public void run() { 
   
                refresh();
            }
        },0,60000);
    }

    /** * 缓存刷新,清除过期数据 */
    public static void refresh(){ 
   
        for (String key : cacheMap.keySet()) { 
   
            if(isExpire(key)){ 
   
                remove(key);
            }
        }
    }

    /** * 加入缓存 * @param key * @param value */
    public static boolean put(String key,Object value){ 
   
        if(key.isEmpty()){ 
   
            return false;
        }
        CacheEntity<Object> cacheEntity = new CacheEntity<>();
        cacheEntity.setCacheTime(0);
        cacheEntity.setValue(value);
        cacheMap.put(key,cacheEntity);
        return true;
    }

    /** * 加入缓存,包含过期时间 * @param key 缓存数据的关键字 * @param value 缓存数据 * @param cacheTime 要缓存的时间 * @param timeUnit 时间单位 */
    public static boolean put(String key, Object value,long cacheTime,TimeUnit timeUnit){ 
   
        if(key.isEmpty()){ 
   
            return false;
        }
        CacheEntity<Object> cacheEntity = new CacheEntity<>();
        cacheEntity.setCacheTime(timeUnit.toMillis(cacheTime));
        cacheEntity.setValue(value);
        cacheMap.put(key,cacheEntity);
        return true;
    }

    /** * 移除缓存数据 * @param key */
    public static boolean remove(String key){ 
   
        if(key.isEmpty()){ 
   
            return false;
        }
        if(!cacheMap.containsKey(key)){ 
   
            return true;
        }
        cacheMap.remove(key);
        return true;
    }

    /** * 获取缓存数据 * @param key * @return */
    public static Object get(String key){ 
   
        if(key.isEmpty()||isExpire(key)){ 
   
            return null;
        }
        CacheEntity cacheEntity = cacheMap.get(key);
        if(null == cacheEntity){ 
   
            return null;
        }
        return cacheEntity.getValue();
    }

    /** * 判断当前数据是否已过期 * @param key * @return */
    private static boolean isExpire(String key){ 
   
        if(key.isEmpty()){ 
   
            return false;
        }
        if(cacheMap.containsKey(key)){ 
   
            CacheEntity cacheEntity = cacheMap.get(key);
            long createTime = cacheEntity.getCreateTime();
            long currentTime = System.currentTimeMillis();
            long cacheTime = cacheEntity.getCacheTime();
            if(cacheTime>0&&currentTime-createTime>cacheTime){ 
   
                return true;
            }
            return false;
        }
        return false;
    }

    /** * 获取当前缓存大小(包含已过期但未清理的数据) * @return */
    public static int getCacheSize(){ 
   
        return cacheMap.size();
    }
}

3. 缓存的测试类

验证缓存对数据的存储,提取及对数据有效性的验证。

import java.util.concurrent.TimeUnit;
/** * 测试类 */
public class Main { 
   

    public static void main(String[] args) throws InterruptedException { 
   

		// try { 
   
		// Class.forName(CacheManager.class.getName());
		// } catch (ClassNotFoundException e) { 
   
		// e.printStackTrace();
		// }

        CacheManager.put("one","第一个数据");
        CacheManager.put("two","第二条数据",50, TimeUnit.SECONDS);
        CacheManager.put("three","第三条数据",3,TimeUnit.MINUTES);

        System.out.println("立刻获取------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        Thread.sleep(55000);
        System.out.println("55秒后------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        Thread.sleep(60000-55000);
        System.out.println("1分钟后------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        Thread.sleep(120000-60000);
        System.out.println("2分钟后------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        Thread.sleep(180000-120000);
        System.out.println("3分钟时------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        Thread.sleep(190000-180000);
        System.out.println("3分钟10秒后------------------------");
        System.out.println(CacheManager.get("one"));
        System.out.println(CacheManager.get("two"));
        System.out.println(CacheManager.get("three"));

        System.out.println("缓存的大小: "+CacheManager.getCacheSize());

        System.out.println("main over------------------------");

    }
}

4.测试结果

测试结果

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/189097.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java中八大基本数据类型详解[通俗易懂]

    Java中八大基本数据类型详解[通俗易懂]自从Java发布以来,基本数据类型就是Java语言的一部分,分别是byte,short,int,long,char,float,double,boolean.当然围绕着这些基本数据类型衍生出来了很多面试题,但是说实话,工作中基本用不到

    2022年7月7日
  • datax(26):各个数据库与datax字段映射

    datax(26):各个数据库与datax字段映射通过源码解读Column-datax中的数据类型,可以知道datax框架中只有7(enumType种)种数据类型,那么各个数据库的字段是如何和datax的字段进行相互映射?一、ADBPGDataX内部类型ADBPG数据类型Longbigint,bigserial,integer,smallint,serialDoubledoubleprecision,float,numeric,realStringvarchar,char,tex.

    2022年5月16日
  • 3nf和bcnf分解_如何分解成3nf

    3nf和bcnf分解_如何分解成3nf1.3NF分解先求出正则覆盖Fc对于Fc里面的所有函数依赖a->b,均转化为Ri=ab对于所有的模式Ri如果包含候选码,进行第4如果都不包含候选码,将任意一个候选码添加到模式Ri里面如果一个模式被另一个模式包含,则去掉此被包含的模式。例子:…

    2022年10月28日
  • CSS 颜色代码大全 CSS颜色对照表[通俗易懂]

    CSS 颜色代码大全 CSS颜色对照表[通俗易懂]转载地址:https://blog.csdn.net/u012117917/article/details/41604711HTML及CSS常用颜色英文词汇  黑色 银色 灰色 白色 茶色 红色 紫色 紫红 black silver gray white maroon …

    2022年5月17日
  • python可变类型有哪些_python可变数据类型有哪些

    python可变类型有哪些_python可变数据类型有哪些将python3的基本数据类型有六种:Number(int,float,bool,complex),String,List,Tuple,Dictionary,Set可变数据类型:list,dic,set不可变数据类型:Number,String,Tuple什么是可变数据类型和不可变数据类型?1、Python中的不可变数据类型,不允许变量的值发生变化,如果改变了变量的值,相当…

    2022年5月20日
  • wing是什么_nativepage原理

    wing是什么_nativepage原理给定 n 本书,编号为 1∼n。在初始状态下,书是任意排列的。在每一次操作中,可以抽取其中连续的一段,再把这段插入到其他某个位置。我们的目标状态是把书按照 1∼n 的顺序依次排列。求最少需要多少次操作。输入格式第一行包含整数 T,表示共有 T 组测试数据。每组数据包含两行,第一行为整数 n,表示书的数量。第二行为 n 个整数,表示 1∼n 的一种任意排列。同行数之间用空格隔开。输出格式每组数据输出一个最少操作次数。如果最少操作次数大于或等于 5 次,则输出 5 or more。每个

    2022年8月9日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号