package com.zq.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class FileCacheUtils {
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class Value{
private Map<String,Object> data=new HashMap<>();
private Date expireTime;
}
@NoArgsConstructor
@AllArgsConstructor
@Data
private static class Node{
private String key;
private Date expireTime;
}
// key:uuid
// value:locationAddress
private static final Logger logger= LoggerFactory.getLogger(FileCacheUtils.class);
private static final Map<String,Value> MAP =new ConcurrentHashMap<>();
private static final PriorityQueue<Node> QUEUE=new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.expireTime.compareTo(o2.expireTime);
}
});
private static final long EXPIRE_TIME=2*60*60*1000;
private static final int MAXSIZE=1000000;
public static Map<String, Object> get(String uuid){
if (uuid==null)
return null;
Value value = MAP.get(uuid);
if(value!=null){
value.setExpireTime(new Date(System.currentTimeMillis()+EXPIRE_TIME));
return value.getData();
}
return null;
}
public static void put(String uuid,Map<String,Object> data){
Date expireTime=new Date(System.currentTimeMillis()+EXPIRE_TIME);
MAP.put(uuid,new Value(data,expireTime));
QUEUE.add(new Node(uuid,expireTime));
logger.info("添加完成,MAP.size="+MAP.size());
cleanSizeExceedData();
}
public static void cleanExpireData(){
Node node=QUEUE.peek();
Date expireTime=new Date(System.currentTimeMillis()-EXPIRE_TIME);
while(node!=null&&node.expireTime.compareTo(expireTime)<0){
MAP.remove(node.getKey());
QUEUE.poll();
node= QUEUE.peek();
}
logger.info("过期清理完成,MAP.size="+MAP.size());
}
public static void cleanSizeExceedData(){
if(MAP.size()<=MAXSIZE)
return;
while(MAP.size()>MAXSIZE){
Node node=QUEUE.poll();
MAP.remove(node.getKey());
}
logger.info("超限请理完成,MAP.size="+MAP.size());
}
//设置定时器,20分组调用一次clean()
@Scheduled(fixedDelay = 20*60*1000)
public void process(){
logger.info("定时器调用,MAP.size="+MAP.size());
cleanSizeExceedData();
cleanExpireData();
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)