map集合實現緩存

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;        }    }}
相關文章
相關標籤/搜索