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

搞定!

相关推荐
Y38153266211 小时前
SERP API + Redis 缓存层:4 种方案对比与选型
数据库·redis·缓存
海兰13 小时前
【高速缓存】RedisVL 高级查询(全文搜索、混合搜索和 多向量搜索)
数据库·人工智能·redis·缓存
流星白龙1 天前
【Redis】4.基本全局命令
数据库·redis·缓存
流星白龙1 天前
【Redis】3.Redis安装与命令行客户端
数据库·redis·缓存
我不想名字重复1 天前
redis缓存和数据库数据保持一致
数据库·redis·缓存
时空无限1 天前
vllm 大模型启动缓存相关环境变量 export
linux·缓存·vllm
流星白龙2 天前
【Redis】6.计数其他命令
数据库·redis·缓存
正儿八经的少年2 天前
redis 的大 key 和热 key 详解
数据库·redis·缓存
X-⃢_⃢-X2 天前
十、Redis之布隆过滤器
数据库·redis·缓存
Database_Cool_2 天前
阿里云 Tair(企业级内存数据库)vs 腾讯云 Redis 云缓存深度对比:性能/数据结构/成本全维度 Benchmark
数据库·阿里云·缓存