Spring Boot 3.x 集成 Caffeine 缓存框架官方指南

文章目录

    • 概述
    • [1. Spring Boot 官方文档中关于 Caffeine 缓存的集成指南](#1. Spring Boot 官方文档中关于 Caffeine 缓存的集成指南)
      • [1.1 基本集成](#1.1 基本集成)
      • [1.2 依赖配置](#1.2 依赖配置)
      • [1.3 启用缓存](#1.3 启用缓存)
      • [1.4 缓存配置](#1.4 缓存配置)
        • [1.4.1 使用缓存规范](#1.4.1 使用缓存规范)
        • [1.4.2 自定义 Bean](#1.4.2 自定义 Bean)
        • [1.4.3 配置 CacheLoader](#1.4.3 配置 CacheLoader)
      • [1.5 缓存管理器自定义](#1.5 缓存管理器自定义)
    • [2. 核心注解使用](#2. 核心注解使用)
      • [2.1 @Cacheable](#2.1 @Cacheable)
      • [2.2 @CachePut](#2.2 @CachePut)
      • [2.3 @CacheEvict](#2.3 @CacheEvict)
    • [3. Caffeine 官方文档中关于 Spring Boot 集成的说明](#3. Caffeine 官方文档中关于 Spring Boot 集成的说明)
      • [3.1 JCache 集成](#3.1 JCache 集成)
      • [3.2 Spring 集成](#3.2 Spring 集成)
      • [3.3 配置示例](#3.3 配置示例)
    • [4. 官方 GitHub 仓库相关信息](#4. 官方 GitHub 仓库相关信息)
      • [4.1 Caffeine 项目信息](#4.1 Caffeine 项目信息)
      • [4.2 项目地址](#4.2 项目地址)
      • [4.3 集成支持](#4.3 集成支持)
    • [5. 完整示例](#5. 完整示例)
      • [5.1 实体类](#5.1 实体类)
      • [5.2 Repository 层](#5.2 Repository 层)
      • [5.3 Service 层](#5.3 Service 层)
      • [5.4 应用配置](#5.4 应用配置)
    • [6. 高级配置](#6. 高级配置)
      • [6.1 多缓存配置](#6.1 多缓存配置)
      • [6.2 缓存统计](#6.2 缓存统计)
      • [6.3 条件缓存](#6.3 条件缓存)
    • [7. 最佳实践](#7. 最佳实践)
      • [7.1 缓存一致性](#7.1 缓存一致性)
      • [7.2 性能优化](#7.2 性能优化)
      • [7.3 错误处理](#7.3 错误处理)
    • [8. 故障排除](#8. 故障排除)
      • [8.1 常见问题](#8.1 常见问题)
      • [8.2 调试技巧](#8.2 调试技巧)
    • 总结

概述

本指南基于官方文档,详细说明如何在 Spring Boot 3.x 中集成和使用 Caffeine 缓存框架。


1. Spring Boot 官方文档中关于 Caffeine 缓存的集成指南

1.1 基本集成

Spring Boot 自动配置缓存基础设施,只要启用缓存支持并使用 @EnableCaching 注解即可 [0†]。

如果类路径中存在 Caffeine,Spring Boot 会自动配置 CaffeineCacheManager(由 spring-boot-starter-cache 启动器提供)[0†]。

1.2 依赖配置

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>3.2.3</version>
</dependency>

1.3 启用缓存

在配置类上添加 @EnableCaching 注解:

java 复制代码
@Configuration
@EnableCaching
public class CacheConfig {
}

1.4 缓存配置

Spring Boot 允许通过多种方式配置 Caffeine 缓存 [0†]:

1.4.1 使用缓存规范

通过 spring.cache.caffeine.spec 属性配置:

properties 复制代码
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
1.4.2 自定义 Bean

定义 CaffeineSpec Bean:

java 复制代码
@Bean
public CaffeineSpec caffeineSpec() {
    return CaffeineSpec.parse("maximumSize=1000,expireAfterWrite=5m");
}
1.4.3 配置 CacheLoader

如果定义了 CacheLoader Bean,它会自动关联到 CaffeineCacheManager

java 复制代码
@Bean
public CacheLoader<Object, Object> cacheLoader() {
    return new CacheLoader<Object, Object>() {
        @Override
        public Object load(Object key) throws Exception {
            // 加载逻辑
            return null;
        }
    };
}

1.5 缓存管理器自定义

通过 CacheManagerCustomizer 接口自定义缓存管理器行为:

java 复制代码
@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
    return (cacheManager) -> cacheManager.setAllowNullValues(false);
}

2. 核心注解使用

2.1 @Cacheable

用于标记方法的结果应该被缓存 [8†]:

java 复制代码
@Service
public class UserService {
    
    @Cacheable(value = "users", key = "#id")
    public User findById(Long id) {
        // 查询逻辑
        return user;
    }
}

2.2 @CachePut

更新缓存但不阻止方法执行:

java 复制代码
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    // 更新逻辑
    return user;
}

2.3 @CacheEvict

从缓存中移除条目:

java 复制代码
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    // 删除逻辑
}

3. Caffeine 官方文档中关于 Spring Boot 集成的说明

3.1 JCache 集成

Caffeine 提供 JSR-107 (JCache) 标准接口的实现 [41†]。通过 JCache,可以在不同缓存实现之间轻松切换。

3.2 Spring 集成

Caffeine 通过 JCache 提供了对 Spring 的集成支持。Spring Cache 从 4.3 版本和 Spring Boot 1.4 版本开始支持 Caffeine [41†]。

3.3 配置示例

java 复制代码
@Configuration
@EnableCaching
public class CaffeineCacheConfig {
    
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(Duration.ofMinutes(5))
            .recordStats());
        return cacheManager;
    }
}

4. 官方 GitHub 仓库相关信息

4.1 Caffeine 项目信息

Caffeine 是一个高性能的缓存库,提供了接近最优的命中率 [3†]。

主要特性

  • 自动加载条目到缓存
  • 基于大小和时间的驱逐策略
  • 异步刷新支持
  • 统计信息收集

4.2 项目地址

4.3 集成支持

Caffeine 提供了多种框架集成:

  • Spring Cache(从 Spring 4.3 和 Boot 1.4 开始)
  • JCache (JSR-107)
  • Guava 适配器 [3†]

5. 完整示例

5.1 实体类

java 复制代码
@Entity
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private BigDecimal price;
    // getters and setters
}

5.2 Repository 层

java 复制代码
public interface ProductRepository extends JpaRepository<Product, Long> {
}

5.3 Service 层

java 复制代码
@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    @Cacheable(key = "#id")
    public Product findById(Long id) {
        return productRepository.findById(id).orElse(null);
    }
    
    @Cacheable(key = "'all'")
    public List<Product> findAll() {
        return productRepository.findAll();
    }
    
    @CachePut(key = "#product.id")
    public Product save(Product product) {
        return productRepository.save(product);
    }
    
    @CacheEvict(key = "#id")
    public void deleteById(Long id) {
        productRepository.deleteById(id);
    }
}

5.4 应用配置

properties 复制代码
# application.properties

# 启用缓存
spring.cache.type=caffeine

# 配置缓存名称
spring.cache.cache-names=products,users

# Caffeine 特定配置
spring.cache.caffeine.spec=maximumSize=1000,expireAfterWrite=10m,recordStats

6. 高级配置

6.1 多缓存配置

java 复制代码
@Configuration
@EnableCaching
public class AdvancedCacheConfig {
    
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        
        // 配置产品缓存
        cacheManager.registerCache("products", Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(Duration.ofMinutes(10))
            .recordStats()
            .build());
        
        // 配置用户缓存
        cacheManager.registerCache("users", Caffeine.newBuilder()
            .maximumSize(500)
            .expireAfterAccess(Duration.ofMinutes(5))
            .recordStats()
            .build());
        
        return cacheManager;
    }
}

6.2 缓存统计

启用统计功能以监控缓存性能:

java 复制代码
@Bean
public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    cacheManager.setCaffeine(Caffeine.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(Duration.ofMinutes(5))
        .recordStats());  // 启用统计
    return cacheManager;
}

6.3 条件缓存

java 复制代码
@Cacheable(value = "products", condition = "#id != null && #id > 0")
public Product findById(Long id) {
    return productRepository.findById(id).orElse(null);
}

7. 最佳实践

7.1 缓存一致性

  • 对于可能被多个实例修改的数据,考虑使用分布式缓存
  • 使用适当的缓存失效策略确保数据一致性

7.2 性能优化

  • 根据访问模式调整缓存大小和过期策略
  • 监控缓存命中率,优化缓存配置
  • 对于高并发场景,考虑使用异步加载

7.3 错误处理

  • 实现适当的异常处理机制
  • 考虑缓存失败时的降级策略

8. 故障排除

8.1 常见问题

  1. 缓存未生效

    • 确认 @EnableCaching 已启用
    • 检查缓存名称是否配置正确
    • 验证方法参数是否正确
  2. 内存泄漏

    • 确保缓存大小有合理上限
    • 监控缓存统计信息
    • 检查缓存过期策略
  3. 性能问题

    • 分析缓存命中率
    • 调整缓存大小和过期时间
    • 考虑异步加载策略

8.2 调试技巧

启用缓存统计以监控性能:

java 复制代码
@Component
public class CacheMonitor {
    
    @EventListener
    public void onCacheEvent(CacheEvent event) {
        // 监控缓存事件
        System.out.println("Cache event: " + event.getType());
    }
}

总结

通过遵循本指南,您可以成功在 Spring Boot 3.x 应用中集成 Caffeine 缓存框架,提高应用的性能和响应速度。关键在于合理配置缓存策略,监控缓存性能,并根据实际使用情况进行优化。

如需更多详细信息,请参考:

相关推荐
像少年啦飞驰点、2 小时前
零基础入门 Redis:从缓存原理到 Spring Boot 集成实战
java·spring boot·redis·缓存·编程入门
虾说羊2 小时前
Springboot中配置欢迎页的方式
java·spring boot·后端
漫漫求2 小时前
Go的panic、defer、recover的关系
开发语言·后端·golang
qq_12498707532 小时前
基于Spring Boot的长春美食推荐管理系统的设计与实现(源码+论文+部署+安装)
java·前端·spring boot·后端·毕业设计·美食·计算机毕业设计
Tony Bai2 小时前
2025 Go 官方调查解读:91% 满意度背后的隐忧与 AI 时代的“双刃剑”
开发语言·后端·golang
不会c+2 小时前
Spring和Springboot的区别
java·spring boot·spring
敲敲千反田2 小时前
redis哨兵和缓存
数据库·redis·缓存
懈尘2 小时前
基于Spring Boot与LangChain4j的AI驱动新闻系统设计与工程实现
java·大数据·人工智能·spring boot·后端·langchain
翔云1234562 小时前
golang中使用 sort.Interface 实现复杂多级排序
开发语言·后端·golang