All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.sylinx.hbatis.plugin.cache.GuavaCacheKit Maven / Gradle / Ivy

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 wrappedObject = cache.get(cacheKey, callable);
			return wrappedObject.isPresent() ? (T) wrappedObject.get() : null;

		} catch (ExecutionException e) {
			GLog.error("get cache error", e);
		}

		return null;
	}

}