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)
上一篇 2026年4月14日 下午6:04
下一篇 2026年4月14日 下午6:10


相关推荐

  • moebius for sql server下载_大数据集群规模选择

    moebius for sql server下载_大数据集群规模选择一、Moebius集群的架构及原理1、无共享磁盘架构Moebius集群采用无共享磁盘架构设计,各个机器可以不连接一个共享的设备,数据可以存储在每个机器自己的存储介质中。这样每个机器就不需要硬件上的

    2022年8月6日
    24
  • 现代汉语常用3500字

    现代汉语常用3500字最近给娃儿取名想着遍历个好名字居然没有完整的3500汉字表就弄了一个现代汉语常用3500字=常见字2500字+次常见字1000字常用字2500字次常用汉字1000字现代汉语常用3500字

    2022年7月1日
    29
  • matplotlib.pyplot.plot()参数详解「建议收藏」

    matplotlib.pyplot.plot()参数详解「建议收藏」https://matplotlib.org/api/pyplot_summary.html在交互环境中查看帮助文档:importmatplotlib.pyplotasplthelp(plt.plot)以下是对帮助文档重要部分的翻译:plot函数的一般的调用形式:#单条线:plot([x],y,[fmt],data=None,**kwargs)#多条线一…

    2022年7月14日
    16
  • 十种常用代码编辑器

    十种常用代码编辑器1.vscode微软推出的轻量级代码编译器,是本人使用最多的编译器(主要是好玩的插件多),支持几乎所有主流的开发语言的语法高亮、智能代码补全、自定义热键、括号匹配、代码片段、代码对比Diff、GIT等特性,支持插件扩展,并针对网页开发和云端应用开发做了优化。分享下本人的死宅背景~2.NETBEANSNetBeans是Sun公司(2009年被甲骨文收购)在2000年创立的开放源代码供开发人员和客户社区的家园,旨在构建世界级的JavaIDE。NetBeans当前可以在Solaris、Win

    2022年6月23日
    150
  • Shipyard 安装

    Shipyard 安装url shttps shipyard project com deploy bash sDeployingSh nbsp gt StartingData nbsp gt StartingDisc nbsp gt StartingCert nbsp gt StartingProx nbsp gt StartingSwa

    2026年3月17日
    3
  • BetterIntelliJ 激活码_在线激活

    (BetterIntelliJ 激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~41MD9IQHZL-eyJsaWNlb…

    2022年3月30日
    108

发表回复

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

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