1. package com.linmingliang.myblog.utils;

    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;

    /**
    * @Author: lml
    * @Date: 2018/6/1 17:15
    * @Description:
    */
    public class MapCache {

    private static final MapCache mapCache;
    private Map<String, CacheObject> map;

    private MapCache() {
    map = new ConcurrentHashMap<>();
    }

    static {
    mapCache = new MapCache();
    }


    public static MapCache getMapCache() {
    return mapCache;
    }

    /**
    * 设置没有过期时间缓存
    *
    * @param key 键
    * @param value 值
    */
    public void set(String key, Object value) {
    this.set(key, value, -1L);
    }

    /**
    * 设置带时间缓存
    *
    * @param key 键
    * @param value 值
    * @param time 缓存时间
    */
    public void set(String key, Object value, Long time) {
    time = time > 0 ? System.currentTimeMillis() / 1000 + time : time;
    CacheObject cacheObject = new CacheObject(key, value, time);
    map.put(key, cacheObject);
    }

    /**
    * 获取缓存
    *
    * @param key
    * @param <T>
    * @return
    */
    public <T> T get(String key) {
    CacheObject cacheObject = map.get(key);
    if (cacheObject != null) {
    Long currentTime = System.currentTimeMillis() / 1000;
    if (cacheObject.getTime() <= 0 || currentTime > cacheObject.getTime()) {
    return (T) cacheObject.getValue();
    }
    }
    return null;
    }

    /**
    * 删除缓存
    *
    * @param key 键
    */
    public void delete(String key) {
    map.remove(key);
    }

    /**
    * 清空缓存
    */
    public void clear() {
    map.clear();
    }

    class CacheObject {
    private String key;
    private Object value;
    private Long time;

    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 getTime() {
    return time;
    }

    public void setTime(Long time) {
    this.time = time;
    }

    public CacheObject(String key, Object value, Long time) {
    this.key = key;
    this.value = value;
    this.time = time;
    }
    }

    }

posted on 2018-06-01 17:41 骑着毛驴追火车 阅读() 评论() 编辑 收藏

版权声明:本文为myDreamWillCometrue原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/myDreamWillCometrue/p/9122716.html