packagewebapp.cache;importjava.util.concurrent.ConcurrentHashMap;importjava.util.concurrent.TimeUnit;/*** @Author:vic
* @Date:Created in 16:55 2019/12/27
* @Description:本地缓存*/
public classLocalCache {/**缓存默认失效时间(毫秒)*/
private static final long DEFAULT_TIMEOUT = 3600*1000;/**缓存清除动作执行间隔(秒)*/
private static final long TASK_TIME = 1;/**缓存存储的map*/
private static final ConcurrentHashMap cacheMap = new ConcurrentHashMap<>();publicLocalCache() {
}private static LocalCache cache = null;public staticLocalCache getInstance() {
//单例一下if (cache == null) {
cache= newLocalCache();new Thread(newTimeoutTimer()).start();
}returncache;
}
//定时器线程-用于检查缓存过期static class TimeoutTimer implementsRunnable{
@Overridepublic voidrun(){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 classCacheEntity {/**值*/
privateObject value;/**过期时间(毫秒)*/
private longexpire;/**创建时的时间戳*/
private longtimeStamp;publicObject getValue() {returnvalue;
}public voidsetValue(Object value) {this.value =value;
}public longgetExpire() {returnexpire;
}public void setExpire(longexpire) {this.expire =expire;
}public longgetTimeStamp() {returntimeStamp;
}public void setTimeStamp(longtimeStamp) {this.timeStamp =timeStamp;
}
}public static boolean set(String key,Object value,longexpire) {
cacheMap.put(key,setEntity(key,value,expire));return true;
}public static booleanset(String key,Object value) {
cacheMap.put(key,setEntity(key,value,DEFAULT_TIMEOUT));return true;
}private static CacheEntity setEntity(String key,Object value,longexpire){
CacheEntity entity= newCacheEntity();
entity.setValue(value);
entity.setExpire(expire);
entity.setTimeStamp(System.currentTimeMillis());returnentity;
}public staticObject get(String key) {
CacheEntity entity=cacheMap.get(key);if (entity == null) {return null;
}else{
Object value=entity.getValue();if (value == null) {return null;
}returnvalue;
}
}public static voidremove(String key) {
cacheMap.remove(key);
}
}