package cn.huge.base.common.utils; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.springframework.util.ObjectUtils; import java.util.concurrent.TimeUnit; /** * 本地缓存工具类 * @author zhouxiantao * @create 2024-09-05 10:51 */ public class GuavaCacheUtils { private static Cache cache = CacheBuilder.newBuilder() //5秒后过期 .expireAfterWrite(5, TimeUnit.SECONDS) // .expireAfterWrite(10, TimeUnit.SECONDS) //最大10个缓存 .maximumSize(10) .build(); private static Cache cacheAi = CacheBuilder.newBuilder() //5秒后过期 .expireAfterWrite(5, TimeUnit.MINUTES) // .expireAfterWrite(10, TimeUnit.SECONDS) //最大10个缓存 .maximumSize(500) .build(); public static Object getCache(String k) { return cache.getIfPresent(k); } public static void putCache(String k, Object value) { cache.put(k, value); } public static Object getCacheAi(String k) { return cacheAi.getIfPresent(k); } public static void putCacheAi(String k, Object value) { cacheAi.put(k, value); } public static void main(String[] args) throws InterruptedException { putCache("15008985673","123456"); while (true){ Thread.sleep(1000); Object cache = getCache("15008985673"); System.out.println(cache); if(ObjectUtils.isEmpty(cache)){ System.out.println("结束。。。"); return; } } } }