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

搞定!

相关推荐
難釋懷19 小时前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard19 小时前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机
时空自由民.21 小时前
STM32的缓存Cache
stm32·嵌入式硬件·缓存
ai_coder_ai1 天前
分布式缓存架构设计与实践
分布式·缓存
Wang's Blog2 天前
AI Agent白手起家23: 大模型速率限制应对与缓存机制实践
人工智能·缓存
网教盟人才服务平台2 天前
Redis Key集中过期引发的流量雪崩实战解析
数据库·redis·缓存
Ivan CloudBay2 天前
网站为什么会使用缓存?
服务器·网络·缓存·云服务器
_oP_i2 天前
Another Redis Desktop Manager更新
数据库·redis·缓存
CryptoPP2 天前
韩国股市数据源对接实战:从KOSPI到KOSDAQ的实时行情接入方案
数据库·redis·缓存·金融·区块链
敲个大西瓜2 天前
Redis一百道核心面试题
数据库·redis·缓存