package com.boot.cache.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LocalExpiringCache {
public static void main(String[] args) {
LocalExpiringCache.getInstance().put("","",100);
}
protected static final Logger log = LoggerFactory.getLogger(LocalExpiringCache.class);
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private static Map<String, CacheItem> cache = null;
private class CacheItem {
private Object value;
private Long expirationTime;
public CacheItem(Object value, long expirationTime) {
this.value = value;
this.expirationTime = expirationTime;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Long getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(Long expirationTime) {
this.expirationTime = expirationTime;
}
}
private static class ExpiringCacheHolder {
private static final LocalExpiringCache INSTANCE = new LocalExpiringCache();
}
public static final LocalExpiringCache getInstance() {
return LocalExpiringCache.ExpiringCacheHolder.INSTANCE;
}
private LocalExpiringCache() {
log.info("正在初始化缓存池.........");
cache = new ConcurrentHashMap<>();
executor.scheduleAtFixedRate(LocalExpiringCache::clearCache, 1000, 1000*50, TimeUnit.MILLISECONDS);
}
public void put(String key, Object value, long expirationSecond) {
long expirationTime = System.currentTimeMillis() + expirationSecond * 1000;
CacheItem item = new CacheItem(value, expirationTime);
cache.put(key, item);
}
public Object get(String key) {
CacheItem item = cache.get(key);
if (item != null && System.currentTimeMillis() < item.getExpirationTime()) {
return item.getValue();
}
return null;
}
public void remove(String key) {
cache.remove(key);
}
public void clear() {
cache.clear();
}
public boolean containsKey(String key) {
return cache.containsKey(key);
}
public boolean isEmpty() {
return cache.isEmpty();
}
public int size() {
return cache.size();
}
private static void clearCache() {
if (cache.size() <= 0) {
return;
}
cache.entrySet().removeIf(entry -> entry.getValue().getExpirationTime() != null && entry.getValue().getExpirationTime() < System.currentTimeMillis());
}
}