Caffeine是一个高性能的Java缓存,有了它完全可以代替Guava Cache,来实现更加高效的缓存;Caffeine采用了W-TinyLFU回收策略,集合了LRU和LFU的优点,提供了一个最佳的命中率,在效率上可以秒杀Guava Cache。
官方性能测试结果:
二、Caffeine使用姿势 1、同步加载import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; private LoadingCache3、异步加载cache = Caffeine.newBuilder() .maximumSize(100L) .refreshAfterWrite(30, TimeUnit.SECONDS) .expireAfterWrite(60, TimeUnit.SECONDS) .build(key -> { log.info("LoadingCache.load begin"); Thread.sleep(2000L); log.info("LoadingCache.load end"); return String.valueOf(number); }); public String getCache(String key) { try { number++; return cache.get(key); } catch (Exception ex) { log.error("TestCache.getCache exception", ex); return null; } }
private AsyncLoadingCache4、使用注解 @Cacheable a、配置caffeineasyncCacheLoader = Caffeine.newBuilder() .maximumSize(100L) .refreshAfterWrite(30, TimeUnit.SECONDS) .expireAfterWrite(60, TimeUnit.SECONDS) .buildAsync(key -> { log.info("AsyncLoadingCache.load begin"); Thread.sleep(2000L); log.info("AsyncLoadingCache.load begin"); return String.valueOf(number); }); public String getAsyncCache(String key) { CompletableFuture future = asyncCacheLoader.get(key); try { return future.get(); } catch (Exception ex) { log.error("TestCache.getAsyncCache exception", ex); return null; } }
spring: cache: type: caffeine caffeine: spec: initialCapacity=10,maximumSize=200,expireAfterWrite=30sb、开启spring cache
启动类添加@EnableCaching
c、代码示例@Cacheable("addCache") public int add(int one, int second) { try { Thread.sleep(2000); } catch (Exception e) { log.error("Calculation.add Exception", e); } return one + second; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)