Java缓存及过期处理的简单实现

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.测试结果

测试结果

猜你喜欢

转载自blog.csdn.net/qq_29550537/article/details/88871493
今日推荐