java 缓存工具类_java实现一个本地缓存工具类

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值