其他分享
首页 > 其他分享> > Caffeine本地缓存Demo

Caffeine本地缓存Demo

作者:互联网

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());
    }

标签:LRU,caffeine,Tiny,性能,开销
来源: