- Gauva基于LRU算法,Caffeine基于W-TinyLFU算法(结合了LRU和LFU的特点) Caffeine支持异步加载 Caffeine性能和开销都优于Guava Caffeine的命中率更高
public class TestCaffeine { public static void main(String[] args) throws Exception { // 1、手动加载 Cache<String, String> cache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10) .build(); cache.put("key1", "test1"); System.out.println("手动加载:" + cache.getIfPresent("key1")); System.out.println("---"); // 2、LoadingCache自动加载 LoadingCache<String, String> cache1 = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10) .build(new CacheLoader<String, String>() { @Override public @Nullable String load(@NonNull String s) throws Exception { return s + "_value"; } }); System.out.println("LoadingCache自动加载:" + cache1.get("key1")); System.out.println("---"); // 3、异步手动加载 AsyncCache<String, String> cache2 = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10) .buildAsync(); CompletableFuture<String> future = cache2.get("key1", key -> { return key + "_value111"; }); System.out.println("异步手动加载:" + future.get()); System.out.println("---"); // 4、异步自动加载 AsyncLoadingCache<String, String> cache3 = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10) .buildAsync(new CacheLoader<String, String>() { @Override public @Nullable String load(@NonNull String s) throws Exception { return s + "_syncvalue"; } }); System.out.println("异步自动加载:" + cache3.get("key3").get()); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/292546.html