package com.liuhuan.cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public abstract class Cache<K, V> {
private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
private static final int MAX_POOL_SIZE = 10;
private static final long KEEP_ALIVE_TIME = 1000L;
private final static int WORK_QUEUE_SIZE = 10;
ListeningExecutorService backgroundRefreshPools =
MoreExecutors.listeningDecorator(new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(WORK_QUEUE_SIZE),
new ThreadFactoryBuilder().setNameFormat("cache-load-thread-%d").build(),
new ThreadPoolExecutor.DiscardPolicy()));
LoadingCache<K, V> cache = CacheBuilder.newBuilder()
.refreshAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(300)
.build(new CacheLoader<K, V>() {
@Override
public V load(K key) throws Exception {
return getValueByKey(key);
}
@Override
public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
return backgroundRefreshPools.submit(() -> getValueByKey(key));
}
});
public V get(K key) {
try {
return cache.get(key);
} catch (Exception e) {
log.info("get cache exception, key:{}, e:{}", key, e);
return null;
}
}
protected abstract V getValueByKey(K key);
protected Map<K, V> loadHotspotData() {
return Maps.newHashMap();
}
@PostConstruct
public void initCache() {
Map<K, V> data = loadHotspotData();
log.info("cache load hotspot data:{}", data);
cache.putAll(data);
}
@PreDestroy
public void destroy() {
try {
backgroundRefreshPools.shutdown();
} catch (Exception e) {
log.error("cache load thread pool showdown exception", e);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!