跳转到主要内容

Java 基于 Caffeine 实现本地缓存

Avatar emanjusaka
统计中…
473
0
Java 基于 Caffeine 实现本地缓存

本文介绍了如何在 Java 项目中使用高性能缓存库 Caffeine 实现本地缓存,包括依赖引入、缓存配置及基本操作方法。


作者:毅念安(Inian / Emanjusaka)|原创,后续会更新修正,转载请保留原文链接。
📝 独立博客:https://www.emanjusaka.com|博客园:https://www.cnblogs.com/emanjusaka|公众号:毅念安

Java 的 Caffeine 是一款高性能的缓存库,用于在内存中高效存储和管理数据。它提供自动加载、灵活的淘汰策略(如基于大小、时间)、异步操作、缓存监控等功能,旨在减少对底层数据源(如数据库)的访问,提升应用性能。与其他缓存库相比,Caffeine 具有更低的延迟和更高的吞吐量,是 Java 应用中实现本地缓存的优秀选择。

引入依赖

        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
          	<version>3.1.8</version>
        </dependency>

SpringBoot 项目可以不用写版本号,SpringBoot 有关于 Caffeine 的版本管理。

代码实现

package com.emanjusaka.localcache;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author emanjusaka
 * @Date 2025/4/28 18:25
 * @Version 1.0
 */
@Component
public class LocalCacheManager implements InitializingBean {
    private Cache<String, String> localCache;

    /**
     * 向缓存中保存数据,如果已经存在不进行覆盖
     *
     * @throws Exception
     */
    public void putIfNotExist(String key, String value) {
        if (localCache.getIfPresent(key) == null) {
            localCache.put(key, value);
        }
    }

    /**
     * 根据 key 获取缓存中的数据,不触发重载
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return localCache.getIfPresent(key);
    }

    /**
     * 根据 key 删除缓存中的数据
     *
     * @param key
     * @return
     */
    public void remove(String key) {
        localCache.invalidate(key);
    }

    /**
     * 在 Bean 初始化时,初始化本地缓存
     */
    @Override
    public void afterPropertiesSet() {
        localCache = Caffeine.newBuilder()
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .expireAfterAccess(1, TimeUnit.HOURS)
                .maximumSize(1000)
                .build();
    }
}


本文由 emanjusaka 创作,发表于 www.emanjusaka.com,采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

❋

微信扫码分享

微博
点赞是美意,赞赏是鼓励。如有帮助,可以关注下微信公众号。
微信 微信
支付宝 支付宝
查看赞赏名单 →
← 上一篇 自定义typeHandler将包含经纬度对象插入到mysql的point类型的字段中 下一篇 → Java 基于 Redis 实现登录频率限制