SpringBoot3.x集成Caffeine缓存框架官方教程
SpringBoot3.x集成Caffeine缓存:添加spring-boot-starter-cache和caffeine依赖,启用@EnableCaching,通过配置或自定义Bean设定缓存规格,支持@Cacheable等核心注解。高级配置包括多缓存策略、统计监控、条件缓存及最佳实践,强调缓存一致性。
概述
本指南完全基于官方文档整理,手把手指导你在 Spring Boot 3.x 中集成 Caffeine 缓存框架。内容直接实用,不涉及多余修饰。

1. Spring Boot 官方文档中关于 Caffeine 缓存的集成指南
1.1 基本集成
Spring Boot 的自动配置能力非常强大——只需在类路径中添加 Caffeine,并加上 @EnableCaching 注解,缓存基础设施便会自动搭建完成 [0†]。这一过程由 spring-boot-starter-cache 启动器隐式配置 CaffeineCacheManager 实现 [0†]。
1.2 依赖配置
首先将依赖引入项目:
org.springframework.boot spring-boot-starter-cache com.github.ben-manes.caffeine caffeine 3.2.3
1.3 启用缓存
在任意配置类上添加 @EnableCaching,缓存功能即被激活:
@Configuration
@EnableCaching
public class CacheConfig {
}
1.4 缓存配置
Spring Boot 提供多种方式配置 Caffeine [0†]:
1.4.1 使用缓存规范
最简单的方法——在 application.properties 中直接配置:
spring.cache.cache-names=cache1,cache2 spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
1.4.2 自定义 Bean
若偏好显式声明,可定义一个 CaffeineSpec Bean:
@Bean
public CaffeineSpec caffeineSpec() {
return CaffeineSpec.parse("maximumSize=1000,expireAfterWrite=5m");
}
1.4.3 配置 CacheLoader
当定义了 CacheLoader Bean 后,它会自动关联到 CaffeineCacheManager,实现自动加载:
@Bean public CacheLoader
1.5 缓存管理器自定义
通过 CacheManagerCustomizer 接口,可进一步定制缓存管理器行为,例如禁止空值:
@Bean public CacheManagerCustomizercacheManagerCustomizer() { return (cacheManager) -> cacheManager.setAllowNullValues(false); }
2. 核心注解使用
2.1 @Cacheable
@Cacheable 是最常用的注解——用于标记方法结果需要被缓存 [8†]。示例如下:
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User findById(Long id) {
// 查询逻辑
return user;
}
}
2.2 @CachePut
与 @Cacheable 不同,@CachePut 只负责更新缓存,方法本身正常执行:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// 更新逻辑
return user;
}
2.3 @CacheEvict
@CacheEvict 用于清除缓存中的条目,例如删除用户后同步清理缓存:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
// 删除逻辑
}
3. Caffeine 官方文档中关于 Spring Boot 集成的说明
3.1 JCache 集成
Caffeine 实现了 JSR-107(即 JCache)标准接口 [41†]。这一设计带来的主要优势是:你可在不同缓存实现之间无缝切换,无需修改业务代码。
3.2 Spring 集成
通过 JCache 层,Caffeine 能够自然地融入 Spring 生态。从 Spring 4.3 和 Spring Boot 1.4 版本起,Spring Cache 就已原生支持 Caffeine [41†]。
3.3 配置示例
若不想使用自动配置,也可手动构建 CacheManager:
@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 是一个高性能的 Java 缓存库,命中率接近理论最优值 [3†]。其核心特性包括:
- 自动加载条目到缓存
- 基于大小和时间的驱逐策略
- 异步刷新支持
- 统计信息收集
4.2 项目地址
- GitHub 仓库:https://github.com/ben-manes/caffeine
- 官方文档:https://github.com/ben-manes/caffeine/wiki
4.3 集成支持
Caffeine 提供多种框架集成方式:
- Spring Cache(自 Spring 4.3 和 Boot 1.4 起)
- JCache (JSR-107)
- Guava 适配器 [3†]
5. 完整示例
理论结合实践,以下提供完整的商品缓存示例。
5.1 实体类
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private BigDecimal price;
// getters and setters
}
5.2 Repository 层
public interface ProductRepository extends JpaRepository{ }
5.3 Service 层
@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 findAll() {
return productRepository.findAll();
}
@CachePut(key = "#product.id")
public Product sa ve(Product product) {
return productRepository.sa ve(product);
}
@CacheEvict(key = "#id")
public void deleteById(Long id) {
productRepository.deleteById(id);
}
}
5.4 应用配置
# 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 多缓存配置
不同业务场景通常需要不同缓存策略。例如商品缓存使用写后过期,用户缓存使用访问后过期:
@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 缓存统计
启用统计后,可以监控缓存表现:
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofMinutes(5))
.recordStats()); // 启用统计
return cacheManager;
}
6.3 条件缓存
有时只需在特定条件下缓存结果:
@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 常见问题
- 缓存未生效
- 确认已添加
@EnableCaching - 检查缓存名称是否拼写错误
- 验证方法参数是否与注解中的 key 表达式匹配
- 确认已添加
- 内存泄漏
- 设定合理的缓存大小上限,防止数据无限膨胀
- 监控缓存统计,观察淘汰是否正常
- 检查过期策略是否生效
- 性能问题
- 分析缓存命中率,低命中率表明缓存未达到预期效果
- 尝试调整缓存大小和过期时间
- 对于冷点数据,考虑异步加载或直接绕过缓存
8.2 调试技巧
开启缓存统计后,可通过监听缓存事件定位问题:
@Component
public class CacheMonitor {
@EventListener
public void onCacheEvent(CacheEvent event) {
// 监控缓存事件
System.out.println("Cache event: " + event.getType());
}
}
总结
按照本指南操作,你应该能够顺利在 Spring Boot 3.x 项目中集成 Caffeine 缓存,从而提升应用响应速度与性能。关键在于:根据业务场景合理配置缓存策略,持续监控命中率,并依据实际运行数据不断优化。缓存并非一次性工作,需要持续打磨。
更多详细内容请参考:
- Spring Boot 官方文档 - 缓存 [0†]
- Caffeine 官方 GitHub 仓库 [3†]
- Caffeine 官方 Wiki [26†]
