【微码】Java 基于 Caffeine 实现本地缓存

本文发布于 2025年04月29日,阅读 7 次,点赞 0 次,归类于 微码
【微码】Java 基于 Caffeine 实现本地缓存

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


博客:https://www.emanjusaka.com
博客园:https://www.cnblogs.com/emanjusaka
公众号: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();
    }
}


本篇完