io.github.dengchen2020.cache.caffeine.CaffeineCacheManager Maven / Gradle / Ivy
package io.github.dengchen2020.cache.caffeine;
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Scheduler;
import io.github.dengchen2020.cache.properties.CacheSpecBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.AbstractCacheManager;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
/**
* caffeine缓存管理器
*
* @author dengchen
* @since 2024/5/28
*/
public class CaffeineCacheManager extends AbstractCacheManager {
private static final Logger log = LoggerFactory.getLogger(CaffeineCacheManager.class);
public CaffeineCacheManager(CacheSpecBuilder cacheSpecBuilder, CaffeineCacheHelper cacheHandler) {
this.cacheSpecBuilder = cacheSpecBuilder;
this.cacheHandler = cacheHandler;
}
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, Thread.ofVirtual().name("caffeine-cache-").factory());
private final CacheSpecBuilder cacheSpecBuilder;
private final CaffeineCacheHelper cacheHandler;
public Cache buildCache(String name, CacheSpecBuilder.CacheSpec cacheSpec) {
if (cacheSpec.isExpireAfterAccess() == null) cacheSpec.setExpireAfterAccess(cacheSpecBuilder.isExpireAfterAccess());
if (cacheSpec.getExpireTime() == null) cacheSpec.setExpireTime(cacheSpecBuilder.getExpireTime());
if (cacheSpec.getMax() == null) cacheSpec.setMax(cacheSpecBuilder.getMax());
if (log.isDebugEnabled()) {
log.debug("缓存名:{},策略:{},最大容量:{}", name, cacheSpec.isExpireAfterAccess() ? "读取后" + cacheSpec.getExpireTime().getSeconds() + "秒后过期" : "写入后" + cacheSpec.getExpireTime().getSeconds() + "秒后过期", cacheSpec.getMax());
}
final Caffeine