本地緩存實現大概思路,單例模式創建本地緩存實例 + 定時器定時掃描緩存是否過期
代碼如下
package webapp.cache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * @Author:vic * @Date:Created in 16:55 2019/12/27 * @Description:本地緩存 */ public class LocalCache { /**緩存默認失效時間(毫秒)*/ private static final long DEFAULT_TIMEOUT = 3600*1000; /**緩存清除動作執行間隔(秒)*/ private static final long TASK_TIME = 1; /**緩存存儲的map*/ private static final ConcurrentHashMap<String,CacheEntity> cacheMap = new ConcurrentHashMap<>(); public LocalCache() { } private static LocalCache cache = null; public static LocalCache getInstance() {
//單例一下 if (cache == null) { cache = new LocalCache(); new Thread(new TimeoutTimer()).start(); } return cache; }
//定時器線程-用於檢查緩存過期 static class TimeoutTimer implements Runnable{ @Override public void run(){ while (true) { try { TimeUnit.SECONDS.sleep(TASK_TIME); for (String key:cacheMap.keySet()) { CacheEntity entity = cacheMap.get(key); long now = System.currentTimeMillis(); if ((now - entity.getTimeStamp()) >= entity.getExpire()) { cacheMap.remove(key); } } } catch (InterruptedException e) { e.printStackTrace(); } } } } /**存儲單元*/ static class CacheEntity { /**值*/ private Object value; /**過期時間(毫秒)*/ private long expire; /**創建時的時間戳*/ private long timeStamp; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public long getExpire() { return expire; } public void setExpire(long expire) { this.expire = expire; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } } public static boolean set(String key,Object value,long expire) { cacheMap.put(key,setEntity(key,value,expire)); return true; } public static boolean set(String key,Object value) { cacheMap.put(key,setEntity(key,value,DEFAULT_TIMEOUT)); return true; } private static CacheEntity setEntity(String key,Object value,long expire){ CacheEntity entity = new CacheEntity(); entity.setValue(value); entity.setExpire(expire); entity.setTimeStamp(System.currentTimeMillis()); return entity; } public static Object get(String key) { CacheEntity entity = cacheMap.get(key); if (entity == null) { return null; } else { Object value = entity.getValue(); if (value == null) { return null; } return value; } } public static void remove(String key) { cacheMap.remove(key); } }
調用示例
String key = "key"; String value = "value"; LocalCache cache = LocalCache.getInstance(); cache.set(key,value,5000); Object result = cache.get(key); System.out.println(result.toString());
