package com.jilongda.common.cache; import com.github.benmanes.caffeine.cache.LoadingCache; import org.springframework.util.StringUtils; import java.util.Objects; /** * @author xiaochen * @ClassName AbstractCaffineCache * @Description * @date 2021-01-11 11:27 */ public class CaffineCache implements CacheTemplate { /** * 缓存环境 */ private String env; /** * 本地缓存实例 */ private LoadingCache loadingCache; /** * 构造函数 * * @param cache */ public CaffineCache(Cache cache) { // 构建本地缓存实例 this.loadingCache = CaffineCacheManage.caffineCacheManage(cache); } /** * 构造函数 * * @param env * @param cache */ public CaffineCache(String env, Cache cache) { this.env = env; this.loadingCache = CaffineCacheManage.caffineCacheManage(cache); } @Override public boolean setKey(String key, T value, long tokenExpireTime) { if (Objects.isNull(this.loadingCache)) { return Boolean.FALSE; } if (StringUtils.hasLength(this.env)) { this.loadingCache.put(this.env + ":" + key, value); } else { this.loadingCache.put(key, value); } return Boolean.TRUE; } @Override public boolean setKey(String key, T value) { return setKey(key, value, 0); } @Override public T getKey(String key) { if (Objects.isNull(this.loadingCache)) { return null; } try { if (StringUtils.hasLength(this.env)) { return (T) this.loadingCache.get(this.env + ":" + key); } else { return (T) this.loadingCache.get(key); } } catch (Exception e) { return null; } } @Override public boolean delKey(String key) { if (Objects.isNull(this.loadingCache)) { return Boolean.FALSE; } if (StringUtils.hasLength(this.env)) { this.loadingCache.invalidate(this.env + ":" + key); } else { this.loadingCache.invalidate(key); } return Boolean.TRUE; } }