Caffeine本地缓存

发布时间 2023-09-25 17:30:05作者: 郭慕荣

简单说,Caffine 是一款高性能的本地缓存组件
由下面三幅图可见:不管在并发读、并发写还是并发读写的场景下,Caffeine 的性能都大幅领先于其他本地开源缓存组件

 

代码如下所示:

package com.example.springbootstudy.test.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author Jelly
 * @Date 2023/9/25 15:44
 */
@Slf4j
public class CaffeineTest {

    public static void main(String[] args) {
        Cache<String, String> cache = Caffeine.newBuilder()
                .initialCapacity(5)
                // 超出时淘汰
                .maximumSize(10)
                //设置写缓存后n秒钟过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                //设置读写缓存后n秒钟过期,实际很少用到,类似于expireAfterWrite
                //.expireAfterAccess(17, TimeUnit.SECONDS)
                .build();

        String orderId = String.valueOf(123456789);
        String orderInfo = cache.get(orderId, key -> getInfo(key));
        System.out.println("00000000000---" + orderInfo);
        System.out.println("11111111111---" + cache.getIfPresent(orderId));

        test1();
    }

    private static String getInfo(String orderId) {
        String info = "";
        // 先查询redis缓存
        log.info("get data from redis");

        // 当redis缓存不存在查db
        log.info("get data from mysql");
        info = String.format("{orderId=%s}", orderId);
        return info;
    }


    public static void test1() {
        // 初始化缓存,设置了 1 分钟的写过期,100 的缓存最大个数
        Cache<Integer, Integer> cache = Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .maximumSize(100)
                .build();

        int key = 1;
        // 使用 getIfPresent 方法从缓存中获取值。如果缓存中不存指定的值,则方法将返回 null
        System.out.println("不存在值,返回null:" + cache.getIfPresent(key));

        // 也可以使用 get 方法获取值,该方法将一个参数为 key 的 Function 作为参数传入。
        // 如果缓存中不存在该 key 则该函数将用于提供默认值,该值在计算后插入缓存中:
        System.out.println("返回默认值:" + cache.get(key, a -> 2));

        // 校验 key 对应的 value 是否插入缓存中
        System.out.println("返回key对应的value:" + cache.getIfPresent(key));

        // 手动 put 数据填充缓存中
        int value = 2;
        cache.put(key, value);

        // 使用 getIfPresent 方法从缓存中获取值。如果缓存中不存指定的值,则方法将返回 null
        System.out.println("返回key对应的value:" + cache.getIfPresent(key));

        // 移除数据,让数据失效
        cache.invalidate(key);
        System.out.println("返回key对应的value:" + cache.getIfPresent(key));
    }


}

总结:

通过对guava cache 和caffeine 从性能到算法及使用的对比中,可以发现Caffeine基本是在Guava的基础上进行优化而来的,提供的功能基本一致,但是通过对算法和部分逻辑的优化,完成了对性能极大的提升,而且我们可以发现,两者切换几乎没有成本,毕竟caffeine就是以替换guava cache为目的而来的。

参考博客:

https://blog.csdn.net/chuige2013/article/details/130940330

https://blog.csdn.net/zhangyunfeihhhh/article/details/108105928