缓存组件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、测试结果

搞定!

相关推荐
XLYcmy4 小时前
核内调度问题的分层优化:缓存管理与性能均衡策略 模型评价 模型缺点与改进方向
缓存·ai·启发式算法·图神经网络·遗传算法·数模·模拟退火
随风一样自由9 小时前
【前端+React+缓存竞态】导航切换缓存刷新机制
前端·react.js·缓存
桌面运维家20 小时前
如何用半缓存云桌面将服务器硬盘容量扩展至本地终端?
运维·服务器·缓存
YOU OU1 天前
Redis初识
数据库·redis·缓存
livemetee1 天前
【关于redis高性能,高可用处理】
数据库·redis·缓存
青山木1 天前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
无小道1 天前
Redis——哨兵
数据库·redis·缓存·哨兵
闪电悠米1 天前
黑马点评-Redis Set-实现关注、取关和共同关注
数据库·redis·缓存
Ricky_Theseus1 天前
CrewAI 生产化:缓存、回调、LLM 配置
java·spring·缓存
风向决定发型丶2 天前
redis集群搭建
数据库·redis·缓存