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

搞定!

相关推荐
小毛驴85011 小时前
redis 如何持久化
数据库·redis·缓存
Kevinyu_17 小时前
Redisson
java·redis·缓存
代码老y18 小时前
Redis 生产实战 7×24:容量规划、性能调优、故障演练与成本治理 40 条军规
数据库·redis·缓存
dexianshen21 小时前
缓存雪崩、缓存穿透,缓存击穿
缓存
许苑向上2 天前
分布式缓存击穿以及本地击穿解决方案
java·分布式·缓存
L_qingting3 天前
Redis 主从复制
数据库·redis·缓存
代码老y3 天前
在百亿流量面前,让“不存在”无处遁形——Redis 缓存穿透的极限攻防实录
数据库·redis·缓存
阿巴~阿巴~3 天前
深入解析:磁盘级文件与内存级(被打开)文件的本质区别与联系
linux·运维·服务器·数据库·缓存
Dajiaonew3 天前
Redis主从同步原理(全量复制、增量复制)
数据库·redis·缓存
秋恬意3 天前
redis红锁
数据库·redis·缓存