美文网首页
Caffeine使用完全示例

Caffeine使用完全示例

作者: 和平菌 | 来源:发表于2021-04-09 17:51 被阅读0次

1、引入依赖包

<dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.8</version>
        </dependency>

2、代码里使用

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

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

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

                @Override
                public @NonNull CompletableFuture<String> 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使用完全示例

      本文链接:https://www.haomeiwen.com/subject/nikwkltx.html