Map实现带失效时间的缓存工具类

import java.util.Iterator;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

public class CacheWithExpireUtil {

// 缓存map

    private static MapcacheMap =new ConcurrentHashMap();

// 缓存有效期map

    private static MapexpireTimeMap =new ConcurrentHashMap();

/**

    * 获取指定的value,如果key不存在或者已过期,则返回null

*

    * @param key

    * @return

    */

    public static Object get(String key) {

if (!cacheMap.containsKey(key)) {

return null;

}

if (expireTimeMap.containsKey(key)) {

if (expireTimeMap.get(key) < System.currentTimeMillis()) {// 缓存失效,已过期

                return null;

}

}

return cacheMap.get(key);

}

/**

    * @param key

    * @param

    * @return

    */

    public static T getT(String key) {

Object obj =get(key);

return obj ==null ?null : (T) obj;

}

/**

    * 设置value(不过期)

    *

    * @param key

    * @param value

    */

    public static void set(String key, Object value) {

cacheMap.put(key, value);

}

/**

    * 设置value

*

    * @param key

    * @param value

    * @param second 过期时间(秒)

    */

    public static void set(final String key, Object value,int second) {

final long expireTime = System.currentTimeMillis() + second *1000;

cacheMap.put(key, value);

expireTimeMap.put(key, expireTime);

if (cacheMap.size() >2) {// 清除过期数据

            new Thread(new Runnable() {

@Override

                public void run() {

// 此处若使用foreach进行循环遍历,删除过期数据,会抛出java.util.ConcurrentModificationException异常

                    Iterator> iterator =cacheMap.entrySet().iterator();

while (iterator.hasNext()) {

Map.Entry entry = iterator.next();

if (expireTimeMap.containsKey(entry.getKey())) {

long expireTime =expireTimeMap.get(key);

if (System.currentTimeMillis() > expireTime) {

iterator.remove();

expireTimeMap.remove(entry.getKey());

}

}

}

}

}).start();

}

}

/**

    * key是否存在

    *

    * @param key

    * @return

    */

    public static boolean isExist(String key) {

return cacheMap.containsKey(key);

}

/**

    * 清除缓存

    *

    * @param key

    */

    public static void remove(String key) {

cacheMap.remove(key);

}

public static void main(String[] args) {

CacheWithExpireUtil.set("testKey_1","testValue_1");

CacheWithExpireUtil.set("testKey_2","testValue_2",10);

CacheWithExpireUtil.set("testKey_3","testValue_3");

CacheWithExpireUtil.set("testKey_4","testValue_4",1);

Object testKey_2 = CacheWithExpireUtil.get("testKey_2");

System.out.println(testKey_2);

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容