缓存组件Caffeine的使用

复制代码
caffeine是一个高性能的缓存组件,在需要缓存数据,但数据量不算太大,不想引入redis的时候,caffeine就是一个不错的选择。可以把caffeine理解为一个简单的redis。

1、导入依赖

XML 复制代码
        <!-- https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine -->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.9.3</version>
        </dependency>

导入是要注意版本,最开始我用的版本是3.1.1,不过启动是的时候会报错,这是因为我用的是jdk1.8,需要降低一下版本,所以就换成了2.9.3

类文件具有错误的版本 55.0, 应为 52.0

请删除该文件或确保该文件位于正确的类路径子目录中。

2、创建测试类

java 复制代码
public class CaffeineTest {

    //创建缓存对象并设置过期时间为10秒
    private static Cache<Integer, String> cache = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(10)).build();

    public static void main(String[] args) throws InterruptedException {
        cache.put(1,"张三");
        cache.put(2,"李四");
        cache.put(3,"王五");

        getTest(1);
        getTest(2);
        getTest(3);
        Thread.sleep(5000);
        getTest(1);
        getTest(2);
        getTest(3);
        Thread.sleep(6000);
        getTest(1);
        getTest(2);
        getTest(3);


    }

    private static void getTest(Integer key) {
        String ifPresent = cache.getIfPresent(key);
        System.out.println(DateUtil.now() +" : "+ ifPresent);
    }
}

测试结果

3、测试结果

搞定!

相关推荐
野生技术架构师1 天前
Redis 和 MySQL 如何保证数据一致性?先更新数据库还是先删缓存,延迟双删、MQ、Canal 一次讲透
数据库·redis·缓存
愈努力俞幸运1 天前
token,context window,top_p,temperature,skill,Harness Engineering
数据库·redis·缓存
Patrick在香港1 天前
Claude API 成本直降90%:Prompt Caching 提示词缓存 Python 实战
python·缓存·prompt
NeilYuen2 天前
【vemory】高性能KV存储AOF方案设计
linux·c++·redis·缓存
LuminousCPP2 天前
数据结构基础篇(二):顺序表与链表全方位对比|从内存布局到 CPU 缓存理解底层差异
c语言·数据结构·经验分享·链表·缓存
spter。2 天前
Redis 与 Single-flight 的分工与协作
数据库·redis·缓存
清水白石0082 天前
Python 如何设计一个线程安全的缓存?从锁策略、LRU 到工程化实战
python·安全·缓存
小宋10212 天前
大模型应用如何控制成本与延迟:Token、缓存、流式和降级实战
人工智能·缓存
番茄炒鸡蛋加糖3 天前
项目技术点总结--四大核心技术+缓存
缓存
大飞记Python3 天前
AI大模型Token计费全解析:输入/输出、缓存命中、阶梯计价一文看懂
人工智能·缓存