栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java用Map实现缓存功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java用Map实现缓存功能

Java用Map实现缓存功能
    • 0.码仙励志
    • 1.自定义缓存工具类
    • 2.测试类

0.码仙励志

你要做多大的事情,就该承受多大的压力。

1.自定义缓存工具类
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ConcurrentHashMapCacheUtils {


    // 用来存放数据
    private static final Map CACHE_OBJECT_MAP = new ConcurrentHashMap();

    
    public boolean set(String key, Object value) {
        try {
            ExpireData expireData = new ExpireData(key, value);
            CACHE_OBJECT_MAP.put(key, expireData);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean set(String key, Object value, long expireMillisecond) {
        try {
            if (expireMillisecond > 0) {
                ExpireData expireData = new ExpireData(key, value, expireMillisecond);
                CACHE_OBJECT_MAP.put(key, expireData);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public Object get(String key) {
        ExpireData expireData = CACHE_OBJECT_MAP.get(key);
        if (expireData == null) {
            return null;
        }
        if (expireData.getExpireMillisecond() == 0) {
            return expireData.getValue();
        }
        long nowTime = System.currentTimeMillis();
        if (nowTime < expireData.getEndTime()) {
            return expireData.getValue();
        } else {
            return null;
        }
    }

    
    public boolean delete(String key) {
        try {
            CACHE_OBJECT_MAP.remove(key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean flush() {
        try {
            CACHE_OBJECT_MAP.clear();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hasKey(String key) {
        try {
            return get(key) == null ? false : true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    
    public long getExpire(String key) {
        ExpireData expireData = CACHE_OBJECT_MAP.get(key);
        if (null == expireData) {
            return 0;
        }
        // 这个代表没有过期时长
        if (expireData.getExpireMillisecond() == 0) {
            return 999999999999999L;
        }
        long expire = expireData.getEndTime() - System.currentTimeMillis();
        if (expire < 0) {
            return 0;
        } else {
            return expire;
        }
    }

    
    public boolean expire(String key, long expireMillisecond) {
        try {
            ExpireData expireData = CACHE_OBJECT_MAP.get(key);
            if (null == expireData) {
                return false;
            }
            if (expireMillisecond > 0) {
                expireData = new ExpireData(key, expireData.getValue(), expireMillisecond);
                CACHE_OBJECT_MAP.put(key, expireData);
            } else {
                set(key, expireData.getValue());
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public List getKeys() {
        List list = new ArrayList();
        for (String key : CACHE_OBJECT_MAP.keySet()) {
            if (hasKey(key)) {
                list.add(key);
            }
        }
        return list;
    }

    
    public void deleteTimeOut() {
        System.out.println(CACHE_OBJECT_MAP.keySet());
        for (String key : CACHE_OBJECT_MAP.keySet()) {
            if (!hasKey(key)) {
                delete(key);
            }
        }
        System.out.println(CACHE_OBJECT_MAP.keySet());
    }

    
    private static class ExpireData {
        private String key; // 键
        private Object value; // 值
        private long expireMillisecond;//过期时长
        private long startTime;//保存时间
        private long endTime;//过期时间

        public ExpireData(String key, Object value) {
            this.key = key;
            this.value = value;
        }

        public ExpireData(String key, Object value, Long expireMillisecond) {
            this.key = key;
            this.value = value;
            this.expireMillisecond = expireMillisecond;
            this.startTime = System.currentTimeMillis();
            this.endTime = startTime + expireMillisecond;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Object getValue() {
            return value;
        }

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

        public long getExpireMillisecond() {
            return expireMillisecond;
        }

        public void setExpireMillisecond(long expireMillisecond) {
            this.expireMillisecond = expireMillisecond;
        }

        public long getStartTime() {
            return startTime;
        }

        public void setStartTime(long startTime) {
            this.startTime = startTime;
        }

        public long getEndTime() {
            return endTime;
        }

        public void setEndTime(long endTime) {
            this.endTime = endTime;
        }
    }

    
    private ConcurrentHashMapCacheUtils() {
        // 反射破解单例模式需要添加的代码
        if (SingletonHolder.hashMapCache != null) {
            throw new RuntimeException();
        }
    }

    
    private static class SingletonHolder {
        private static final ConcurrentHashMapCacheUtils hashMapCache = new ConcurrentHashMapCacheUtils();
    }

    
    public static ConcurrentHashMapCacheUtils getHashMapCache() {
        return SingletonHolder.hashMapCache;
    }

    
    private Object readResolve() {
        return SingletonHolder.hashMapCache;
    }

}

2.测试类
public class Test {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMapCacheUtils hashMapCache1 = ConcurrentHashMapCacheUtils.getHashMapCache();
        ConcurrentHashMapCacheUtils hashMapCache2 = ConcurrentHashMapCacheUtils.getHashMapCache();
        System.out.println("==========测试返回的是否是同一个对象============");
        System.out.println(hashMapCache1 == hashMapCache2);
        System.out.println("===========测试普通新增 和 获取===========");
        System.out.println(hashMapCache1.set("aa", "aaa"));
        System.out.println(hashMapCache2.get("aa"));
        System.out.println(hashMapCache1.set("aa", "aaaa"));
        System.out.println(hashMapCache2.get("aa"));
        System.out.println("===========测试指定有效时长新增===========");
        System.out.println(hashMapCache1.set("bb", "bbb", 5000));
        System.out.println(hashMapCache2.get("bb"));
        Thread.sleep(2000);
        System.out.println(hashMapCache2.get("bb"));
        Thread.sleep(2000);
        System.out.println(hashMapCache2.get("bb"));
        Thread.sleep(2000);
        System.out.println(hashMapCache2.get("bb"));
        System.out.println("===========测试判断key是否存在 和 删除===========");
        System.out.println(hashMapCache1.hasKey("cc"));
        System.out.println(hashMapCache1.delete("cc"));
        System.out.println(hashMapCache1.hasKey("cc"));
        System.out.println(hashMapCache1.set("cc", "cc"));
        System.out.println(hashMapCache1.hasKey("cc"));
        System.out.println(hashMapCache1.delete("cc"));
        System.out.println(hashMapCache1.hasKey("cc"));
        System.out.println("==========测试全局删除============");
        System.out.println(hashMapCache1.set("dd1", "ddd1"));
        System.out.println(hashMapCache1.set("dd2", "ddd2"));
        System.out.println(hashMapCache1.hasKey("dd1"));
        System.out.println(hashMapCache1.hasKey("dd2"));
        System.out.println(hashMapCache1.flush());
        System.out.println(hashMapCache1.hasKey("dd1"));
        System.out.println(hashMapCache1.hasKey("dd2"));
        System.out.println(hashMapCache1.set("dd1", "ddd1"));
        System.out.println(hashMapCache1.set("dd2", "ddd2"));
        System.out.println(hashMapCache1.hasKey("dd1"));
        System.out.println(hashMapCache1.hasKey("dd2"));
        System.out.println("===========测试根据key获取还有多长时间过期===========");
        System.out.println(hashMapCache1.getExpire("ee1"));
        System.out.println(hashMapCache1.set("ee1", "eee1", 5000));
        System.out.println(hashMapCache1.set("ee2", "eee2"));
        System.out.println(hashMapCache1.getExpire("ee1"));
        System.out.println(hashMapCache1.getExpire("ee2"));
        Thread.sleep(2000);
        System.out.println(hashMapCache1.getExpire("ee1"));
        Thread.sleep(2000);
        System.out.println(hashMapCache1.getExpire("ee1"));
        Thread.sleep(2000);
        System.out.println(hashMapCache1.getExpire("ee1"));
        Thread.sleep(2000);
        System.out.println(hashMapCache1.getExpire("ee1"));
        System.out.println("===========测试指定缓存失效时间===========");
        System.out.println(hashMapCache1.expire("ff1", 5000));
        System.out.println(hashMapCache1.set("ff2", "fff2", 5000));
        Thread.sleep(3000);
        System.out.println(hashMapCache1.getExpire("ff2"));
        System.out.println(hashMapCache1.expire("ff2", 6000));
        System.out.println(hashMapCache1.getExpire("ff2"));
        Thread.sleep(3000);
        System.out.println(hashMapCache1.getExpire("ff2"));
        System.out.println(hashMapCache1.set("ff3", "fff3"));
        System.out.println(hashMapCache1.getExpire("ff3"));
        System.out.println(hashMapCache1.expire("ff3", 6000));
        System.out.println(hashMapCache1.getExpire("ff3"));
        Thread.sleep(3000);
        System.out.println(hashMapCache1.getExpire("ff3"));
        System.out.println(hashMapCache1.expire("ff3", 0));
        System.out.println(hashMapCache1.getExpire("ff3"));
        System.out.println("===========测试获取所有的键 和 删除过期的缓存===========");
        System.out.println(hashMapCache1.set("gg1", "ggg1"));
        System.out.println(hashMapCache1.set("gg2", "ggg2", 3000));
        System.out.println(hashMapCache1.getKeys());
        Thread.sleep(4000);
        System.out.println(hashMapCache1.getKeys());
        hashMapCache1.deleteTimeOut();
    }
}

参考文献:
https://cloud.tencent.com/developer/article/1613976
https://blog.csdn.net/qq_35030994/article/details/80871279

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/459725.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号