1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| package com.xfktech.nurse.platform.config.utils;
import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
public class LocalCacheUtil {
private static Map<String, Object> cacheMap = new ConcurrentHashMap<String, Object>(); private static Map<String, Long> expireTimeMap = new ConcurrentHashMap<String, Long>();
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); }
public static <T> T getT(String key) { Object obj = get(key); return obj == null ? null : (T) obj; }
public static void set(String key, Object value) { cacheMap.put(key, value); }
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() { Iterator<Map.Entry<String, Object>> iterator = cacheMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); if (expireTimeMap.containsKey(entry.getKey())) { long expireTime = expireTimeMap.get(key); if (System.currentTimeMillis() > expireTime) { iterator.remove(); expireTimeMap.remove(entry.getKey()); } } } } }).start(); } }
public static boolean isExist(String key) { return cacheMap.containsKey(key); }
public static void remove(String key) { cacheMap.remove(key); }
public static void main(String[] args) { LocalCacheUtil.set("testKey_1", "testValue_1"); LocalCacheUtil.set("testKey_2", "testValue_2", 10); LocalCacheUtil.set("testKey_3", "testValue_3"); LocalCacheUtil.set("testKey_4", "testValue_4", 1); Object testKey_2 = LocalCacheUtil.get("testKey_2"); System.out.println(testKey_2); }
}
|