package com.tanpu.community.cache; import com.tanpu.common.exception.BizException; import com.tanpu.common.util.JsonUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.function.Supplier; @Service public class LocalCache { @Autowired private CaffeineCacheManager cacheManager; private Cache localCache; @PostConstruct public void init() { localCache = cacheManager.getCache("local"); if (localCache == null) { throw new BizException("local cache not found!"); } } public <T> T getObject(String key, Class<T> clz) { return localCache.get(key, clz); } public <T> void putObject(String key, T value) { localCache.put(key, value); } public<T> T getObject(String key, Supplier<T> func, Class<T> clz) { T value = localCache.get(key, clz); if (value != null) { return value; } T ret = func.get(); if (ret != null) { localCache.put(key, ret); } return ret; } }