cn.sylinx.hbatis.plugin.cache.GuavaCacheKit Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hbatis-core Show documentation
Show all versions of hbatis-core Show documentation
hbatis is a simple orm framework
The newest version!
package cn.sylinx.hbatis.plugin.cache;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import cn.sylinx.hbatis.db.cache.ICacheKit;
import cn.sylinx.hbatis.db.cache.IDataLoader;
import cn.sylinx.hbatis.log.GLog;
class GuavaCacheKit implements ICacheKit {
private Cache> cache;
public GuavaCacheKit() {
this(new GuavaCacheConfig());
}
public GuavaCacheKit(GuavaCacheConfig guavaCacheConfig) {
cache = CacheBuilder.newBuilder()
// 默认5分钟过期
.expireAfterWrite(Duration.ofMinutes(guavaCacheConfig.getExpireAfterWrite()))
// 最大2000个缓存键
.maximumSize(guavaCacheConfig.getMaximumSize()).build();
}
@Override
public boolean isInited() {
return true;
}
@SuppressWarnings("unchecked")
@Override
public T get(String cacheKey, IDataLoader dataLoader) {
// 解决guava返回为空值报错的问题
// CacheLoader returned null for key xxxxx
Callable> callable = () -> {
GLog.debug("loaded from db, cache key: {} ", cacheKey);
return Optional.ofNullable(dataLoader.load());
};
try {
Optional