高性能缓存Caffeine的基本使用方式

介绍

Caffeine是基于JDK1.8版本的高性能本地缓存库,它是Guava的增强版,与ConcurrentLinkedHashMap相似,支持并发,并且可以在O(1)的时间复杂度内查找、写入元素。

性能比对

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

使用方式

一、Population(缓存类型)

1.Cache

private static void manual() {
   
   
    // 构建caffeine的缓存对象,并指定在写入后的10分钟内有效,且最大允许写入的条目数为10000
    Cache<String, String> cache = Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .build();
    String key = "hello";
    // 查找某个缓存元素,若找不到则返回null
    String str = cache.getIfPresent(key);
    System.out.println("cache.getIfPresent(key) ---> " + str);
    // 查找某个缓存元素,若找不到则调用函数生成,如无法生成则返回null
    str = cache.get(key, k -> create(key));
    System.out.println("cache.get(key, k -> create(key)) ---> " + str);
    // 添加或者更新一个缓存元素
    cache.put(key, str);
    System.out.println("cache.put(key, str) ---> " + cache.getIfPresent(key));
    // 移除一个缓存元素
    cache.invalidate(key);
    System.out.println("cache.invalidate(key) ---> " + cache.getIfPresent(key));
}


private static String create(Object key) {
   
   
    return key + " world";
}

输出结果:

cache.getIfPresent(key) ---> null
cache.get(key, k -> create(key)) ---> hello world
cache.put(key, str) ---> hello world
cache.invalidate(key) ---> null

2.Loading

LoadingCache是附加在CacheLoader之上构建的缓存对象。

可以使用getAll方法执行批量查找,默认情况下,getAll()方法会单独调用CacheLoader.load()方法来加载每个不在缓存中的Key,必要情况下可以重写CacheLoader.loadAll()方法来弥补其缺陷。

public static void loading() {
   
   
    LoadingCache<String, String> cache = Caffeine.newBuilder()
            .maximumSize(10_000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(key -> create(key)); // 当调用get或者getAll时,若找不到缓存元素,则会统一调用create(key)生成
    String key = "hello";
    String str = cache.get(key);
    System.out.println("cache.get(key) ---> " + str);
    List<String> keys = Lists.newArrayList("a", "b", "c", "d", "e");
    // 批量查找缓存元素,如果缓存不存在则生成缓存元素
    Map<String, String> maps = cache.getAll(keys);
    System.out.println("cache.getAll(keys) ---> " + maps);
}

private static String create(Object key) {
   
   
    return key + " world";
}

输出结果

cache.get(key) ---> hello world
cache.getAll(keys) ---> {a=a world, b=b world, c=c world, d=d world, e=e world}

3.Asynchronous (Manual)

AsyncCache就是Cache的异步实现方式,提供了通过Executor生成缓存元素并返回CompletableFuture的能力。
synchronous()提供了在缓存计算完成前的阻塞能力,AsyncCache默认使用ForkJoinPool.commonPool()线程池,你也可以通过重写Caffeine.executor(executor)来实现自己的线程池。

private static void asynchronous() {
   
   
    AsyncCache<String, String> cache = Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .buildAsync();
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值