依赖于ScheduledThreadPoolExecutor 及ConcurrentMap实现
适合无法使用Redis情况下的小数据量缓存
代码如下
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.lang.reflect.Type;
import java.util.concurrent.*;
@Component
public class CacheUtil {
private final static ConcurrentMap<String, Object> cacheMap = new ConcurrentHashMap<>();
public static ScheduledThreadPoolExecutor scheduledExecutor;
public static void set(String key, Object value) {
cacheMap.put(key, value);
}
public static void set(String key, Object value, int time, TimeUnit timeUnit) {
set(key, value);
setTimeOut(key, time, timeUnit);
}
public static void setTimeOut(String key, int time, TimeUnit timeUnit) {
scheduledExecutor.schedule(new ClearCacheRunnable(key), time, timeUnit);
}
public static void remove(String key) {
cacheMap.remove(key);
}
public static boolean hasKey(String key) {
return cacheMap.containsKey(key);
}
public static <T> T get(String key) {
if (!hasKey(key)) return null;
return (T) cacheMap.get(key);
}
public static <T> T get(String key, Type type) {
if (!hasKey(key)) return null;
return JSON.parseObject(JSON.toJSONString(cacheMap.get(key)), type);
}
public static <T> T get(String key, TypeReference<T> typeReference) {
if (!hasKey(key)) return null;
return JSON.parseObject(JSON.toJSONString(cacheMap.get(key)), typeReference);
}
@Bean(name = "CacheUtilTaskExecutor")
public void init() {
ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(15);
scheduledExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
CacheUtil.scheduledExecutor = scheduledExecutor;
}
private static class ClearCacheRunnable implements Runnable {
private final String key;
public ClearCacheRunnable(String key) {
this.key = key;
}
@Override
public void run() {
CacheUtil.remove(key);
}
}
}