在 Spring Boot 中集成 Caffeine 缓存

在 Spring Boot 中集成 Caffeine 缓存可以显著提升应用性能,适用于本地内存缓存场景。Caffeine 是一个高性能的 Java 缓存库,支持 TTL(过期时间)、最大条目数、淘汰策略等特性。



✅ 一、添加依赖

Maven:

<!-- pom.xml -->
<dependencies>
    <!-- Spring Cache 支持 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <!-- Caffeine 缓存库 -->
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
</dependencies>

Gradle:

// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    implementation 'com.github.ben-manes.caffeine:caffeine'
}


✅ 二、启用缓存功能

在主类或配置类上添加 @EnableCaching 注解以启用缓存支持:

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


✅ 三、配置 CaffeineCacheManager

创建一个配置类,定义缓存管理器并设置过期时间和最大条目数:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.ben.manes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("userCache", "tokenCache");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(100) // 最大缓存条目数
                .expireAfterWrite(10, TimeUnit.MINUTES)); // 写入后10分钟过期
        return cacheManager;
    }
}


✅ 四、使用缓存注解

在业务逻辑中通过注解方式使用缓存,例如:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable("userCache")
    public User getUserById(Long id) {
        // 模拟数据库查询
        System.out.println("Fetching user from DB...");
        return new User(id, "User" + id);
    }
}

其他常用注解包括:

注解说明
@Cacheable根据方法参数缓存结果
@CachePut更新缓存
@CacheEvict清除缓存


✅ 五、动态调整缓存配置(可选)

你也可以将缓存配置抽取到 application.yml 中,实现更灵活的配置化管理:

caffeine:
  cache:
    userCache:
      maximum-size: 200
      expire-after-write: 30m
    tokenCache:
      maximum-size: 50
      expire-after-write: 1h

然后通过自定义配置类解析这些值进行初始化。



🧩 示例:完整结构图

src/
├── main/
│   ├── java/
│   │   └── com.example.demo/
│   │       ├── Application.java
│   │       ├── config/
│   │       │   └── CacheConfig.java
│   │       ├── service/
│   │       │   └── UserService.java
│   │       └── model/
│   │           └── User.java
│   └── resources/
│       └── application.yml


🔍 总结对比

功能是否支持备注
基于内存✅ 是本地缓存
线程安全✅ 是高并发友好
TTL 过期机制✅ 是可配置写入/访问过期时间
最大条目限制✅ 是支持 LRU 淘汰策略
Spring 集成支持✅ 是提供 CaffeineCacheManager
分布式缓存❌ 否适合单机部署,如需分布式请用 Redis


💡 小贴士

  • 使用 @Cacheable(key = "#id") 显式指定 key,避免因参数类型导致冲突。
  • 可结合 @Scheduled 定时任务做缓存预热或清理。
  • 若项目中有多个缓存区域,建议统一在 CacheConfig 中集中配置。


本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):

昵称:
邮箱:
内容: