You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.4 KiB
74 lines
2.4 KiB
import java.util.concurrent.ConcurrentHashMap;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.ScheduledExecutorService;
|
|
import java.util.concurrent.TimeUnit;
|
|
public class Cache {
|
|
private final ConcurrentHashMap<Object,CacheNode> map;
|
|
private final long timeOut;
|
|
private ScheduledExecutorService thread;
|
|
//无参构造永久不过期
|
|
public Cache(){
|
|
this(0);
|
|
}
|
|
//有参构造设置过期时间
|
|
public Cache(long timeOut){
|
|
map = new ConcurrentHashMap<>();
|
|
this.timeOut = timeOut;
|
|
//定时清理过期数据
|
|
thread = Executors.newSingleThreadScheduledExecutor();
|
|
thread.scheduleAtFixedRate(this::clearTimeOut,2,2,TimeUnit.SECONDS);
|
|
}
|
|
//存入缓存
|
|
public void put(Object key,Object value){
|
|
put(key,value,timeOut);
|
|
}
|
|
//自定义过期时间存放
|
|
public void put(Object key,Object value,long ttl){
|
|
long endTime = ttl == 0 ? Long.MAX_VALUE : System.currentTimeMillis()+ttl;
|
|
map.put(key,new CacheNode(value,endTime));
|
|
}
|
|
//获取缓存
|
|
public Object get(Object key){
|
|
CacheNode node = map.get(key);
|
|
if(node == null){
|
|
return null;
|
|
}
|
|
//判断是否过期
|
|
if(System.currentTimeMillis()>node.endTime){
|
|
map.remove(key);
|
|
return null;
|
|
}
|
|
return node.value;
|
|
}
|
|
//删除缓存
|
|
public void remove(Object key){
|
|
map.remove(key);
|
|
}
|
|
//清理过期数据
|
|
private void clearTimeOut(){
|
|
map.entrySet().removeIf(e->System.currentTimeMillis()>e.getValue().endTime);
|
|
}
|
|
//关闭线程防止资源泄露
|
|
public void close(){
|
|
thread.shutdown();
|
|
}
|
|
//内部存储节点
|
|
private static class CacheNode{
|
|
Object value;
|
|
long endTime;
|
|
public CacheNode(Object value,long endTime){
|
|
this.value = value;
|
|
this.endTime = endTime;
|
|
}
|
|
}
|
|
//测试运行
|
|
public static void main(String[] args) throws InterruptedException {
|
|
//设置5秒过期
|
|
Cache cache = new Cache(5000);
|
|
cache.put("学号","2026001");
|
|
System.out.println("存入立刻获取:"+cache.get("学号"));
|
|
Thread.sleep(6000);
|
|
System.out.println("6秒后获取(已过期):"+cache.get("学号"));
|
|
cache.close();
|
|
}
|
|
}
|