Caffeine使用完全示例

1、引入依赖包


            com.github.ben-manes.caffeine
            caffeine
            2.8.8
        

2、代码里使用

private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(4,
            4,
            2,
            TimeUnit.MINUTES,
            new LinkedBlockingDeque<>(), new ThreadFactoryBuilder().build());

    private static LoadingCache localCache = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.MINUTES) //10分钟淘汰掉
            .refreshAfterWrite(1, TimeUnit.SECONDS)
            .build(new CacheLoader() {

                @Nullable
                @Override
                public String load(@NonNull String token) throws Exception {
                    return "直接获取数据";
                }

                @Override
                public @NonNull CompletableFuture asyncReload(@NonNull String key, @NonNull String oldValue, @NonNull Executor executor) {
                    System.out.println("自动刷新缓存");

                    return CompletableFuture.supplyAsync(() -> {
                        System.out.println("执行异步刷新");
                        return "异步刷新的值";
                    },executorService);
                }
            });


    public static void main(String[] args) throws InterruptedException {
        System.out.println(getValue("1"));
        Thread.sleep(2000);
        System.out.println(getValue("1"));
        Thread.sleep(2000);
        System.out.println(getValue("1"));
    }

    public static String getValue(String key) {
        return localCache.get(key);
    }

你可能感兴趣的:(Caffeine使用完全示例)