cache_patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpring Boot Cache Abstraction
Spring Boot Cache抽象
Overview
概述
Spring Boot ships with a cache abstraction that wraps expensive service calls
behind annotation-driven caches. This abstraction supports multiple cache
providers (ConcurrentMap, Caffeine, Redis, Ehcache, JCache) without changing
business code. The skill provides a concise workflow for enabling caching,
managing cache lifecycles, and validating behavior in Spring Boot 3.5+ services.
Spring Boot 自带了缓存抽象层,通过注解驱动的缓存来包装开销较大的服务调用。该抽象层支持多种缓存提供者(ConcurrentMap、Caffeine、Redis、Ehcache、JCache),且无需修改业务代码。本指南提供了在Spring Boot 3.5+服务中启用缓存、管理缓存生命周期以及验证缓存行为的简洁流程。
When to Use
适用场景
- Add ,
@Cacheable, or@CachePutto Spring Boot service methods.@CacheEvict - Configure Caffeine, Redis, or JCache cache managers for Spring Boot.
- Diagnose cache invalidation, eviction scheduling, or cache key issues.
- Expose cache management endpoints or scheduled eviction routines.
Use trigger phrases such as "implement service caching", "configure
CaffeineCacheManager", "evict caches on update", or "test Spring cache
behavior" to load this skill.
- 为Spring Boot服务方法添加、
@Cacheable或@CachePut注解。@CacheEvict - 为Spring Boot配置Caffeine、Redis或JCache缓存管理器。
- 诊断缓存失效、驱逐调度或缓存键相关问题。
- 暴露缓存管理端点或调度缓存驱逐任务。
使用触发短语如**“实现服务缓存”、“配置CaffeineCacheManager”、“更新时驱逐缓存”或“测试Spring缓存行为”**来调用本指南。
Prerequisites
前置条件
- Java 17+ project based on Spring Boot 3.5.x (records encouraged for DTOs).
- Dependency ; add provider-specific starters as needed (
spring-boot-starter-cache,spring-boot-starter-data-redis,caffeine, etc.).ehcache - Constructor-injected services that expose deterministic method signatures.
- Observability stack (Actuator, Micrometer) when operating caches in production.
- 基于Spring Boot 3.5.x的Java 17+项目(推荐使用records作为DTO)。
- 依赖;根据需要添加特定提供者的启动器(
spring-boot-starter-cache、spring-boot-starter-data-redis、caffeine等)。ehcache - 使用构造函数注入的服务,且方法签名具有确定性。
- 在生产环境中操作缓存时,需要可观测性栈(Actuator、Micrometer)。
Quick Start
快速开始
-
Add dependenciesxml
<!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <!-- Optional: Caffeine --> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </dependency>gradleimplementation "org.springframework.boot:spring-boot-starter-cache" implementation "com.github.ben-manes.caffeine:caffeine" -
Enable cachingjava
@Configuration @EnableCaching class CacheConfig { @Bean CacheManager cacheManager() { return new CaffeineCacheManager("users", "orders"); } } -
Annotate service methodsjava
@Service @CacheConfig(cacheNames = "users") class UserService { @Cacheable(key = "#id", unless = "#result == null") User findUser(Long id) { ... } @CachePut(key = "#user.id") User refreshUser(User user) { ... } @CacheEvict(key = "#id", beforeInvocation = false) void deleteUser(Long id) { ... } } -
Verify behavior
- Run focused unit tests that call cached methods twice and assert repository invocations.
- Inspect Actuator endpoint (if enabled) for hit/miss counters.
cache
-
添加依赖xml
<!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <!-- 可选:Caffeine --> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </dependency>gradleimplementation "org.springframework.boot:spring-boot-starter-cache" implementation "com.github.ben-manes.caffeine:caffeine" -
启用缓存java
@Configuration @EnableCaching class CacheConfig { @Bean CacheManager cacheManager() { return new CaffeineCacheManager("users", "orders"); } } -
为服务方法添加注解java
@Service @CacheConfig(cacheNames = "users") class UserService { @Cacheable(key = "#id", unless = "#result == null") User findUser(Long id) { ... } @CachePut(key = "#user.id") User refreshUser(User user) { ... } @CacheEvict(key = "#id", beforeInvocation = false) void deleteUser(Long id) { ... } } -
验证行为
- 运行聚焦单元测试,两次调用缓存方法并断言仓库调用情况。
- 检查Actuator的端点(若已启用)的命中/未命中计数器。
cache
🔄 Workflow
🔄 工作流程
Aşama 1: Strategy & Provider Selection
步骤1:策略与提供者选择
- Identifying Hot Paths: En çok beklenen ve nadir değişen veri okuma (I/O) noktalarını belirle.
- Provider Selection: Bellek içi (Caffeine) veya dağıtık (Redis) cache seçimine karar ver.
- Key Design: SpEL kullanarak benzersiz ve tahmin edilebilir cache key strategy'si oluştur.
- 识别热点路径:确定最频繁访问且极少变化的数据读取(I/O)点。
- 选择提供者:决定使用内存缓存(Caffeine)还是分布式缓存(Redis)。
- 键设计:使用SpEL创建唯一且可预测的缓存键策略。
Aşama 2: Annotation Implementation
步骤2:注解实现
- @Cacheable: Veriyi cache'e yaz we sonraki çağrılarda oradan oku.
- @CachePut: Veri güncellendiğinde cache'i de yenile.
- @CacheEvict: Silme işlemlerinde veya belirli periyotlarda cache'i temizle (opsiyonunu değerlendir).
allEntries=true
- @Cacheable:将数据写入缓存,后续调用时从缓存读取。
- @CachePut:数据更新时同步刷新缓存。
- @CacheEvict:在删除操作或特定周期内清除缓存(考虑使用选项)。
allEntries=true
Aşama 3: LifeCycle & Monitoring
步骤3:生命周期与监控
- TTL/Eviction: Veri tazeliği (TTL) ve temizleme (Eviction) politikalarını (LRU/LFU) konfigüre et.
- Actuator Audit: endpoint'i üzerinden hit/miss oranlarını izle.
cache - Integration Testing: ile cache izolasyonunu ve tutarlılığını test et.
@SpringBootTest
- TTL/驱逐:配置数据新鲜度(TTL)和驱逐策略(LRU/LFU)。
- Actuator审计:通过端点监控命中/未命中比率。
cache - 集成测试:使用测试缓存隔离性和一致性。
@SpringBootTest
Kontrol Noktaları
检查点
| Aşama | Doğrulama |
|---|---|
| 1 | Transactional işlemler sırasında cache tutarlılığı (Data drift) bozuluyor mu? |
| 2 | "Cache-aside" veya "ReadOnly" stratejisi doğru uygulandı mı? |
| 3 | Çoklu instance yapısında "Cache Stampede" riski önlendi mi? |
Cache Patterns v2.0 - With Workflow
| 步骤 | 验证内容 |
|---|---|
| 1 | 事务操作期间缓存一致性(数据漂移)是否被破坏? |
| 2 | “Cache-aside”或“ReadOnly”策略是否正确实现? |
| 3 | 多实例架构中是否避免了“缓存雪崩”风险? |
缓存模式v2.0 - 包含工作流程
Advanced Options
高级选项
- Integrate JCache annotations when interoperating with providers that favor
JSR-107 (,
@CacheResult). Avoid mixing with Spring annotations on the same method.@CacheRemove - Cache reactive return types (,
Mono) orFluxvalues. Spring stores resolved values and resubscribes on hits; consider TTL alignment with publisher semantics.CompletableFuture - Apply HTTP caching headers using when exposing cached responses via REST.
CacheControl
- 当与支持JSR-107的提供者交互时,集成JCache注解(、
@CacheResult)。避免在同一方法上混合使用Spring注解和JCache注解。@CacheRemove - 缓存响应式返回类型(、
Mono)或Flux值。Spring会存储解析后的值,并在命中时重新订阅;需考虑TTL与发布者语义对齐。CompletableFuture - 当通过REST暴露缓存响应时,使用设置HTTP缓存头。
CacheControl
Examples
示例
- Load for progressive scenarios (basic product cache, conditional caching, multilevel eviction, Redis integration).
references/cache-examples.md - Load for annotation matrices, configuration tables, and property samples.
references/cache-core-reference.md
- 加载查看进阶场景(基础产品缓存、条件缓存、多级驱逐、Redis集成)。
references/cache-examples.md - 加载查看注解矩阵、配置表和属性示例。
references/cache-core-reference.md
References
参考资料
- : curated excerpts from the Spring Framework Reference Guide (official).
references/spring-framework-cache-docs.md - : narrative overview extracted from Spring documentation.
references/spring-cache-doc-snippet.md - : annotation parameters, dependency matrices, property catalogs.
references/cache-core-reference.md - : end-to-end examples with tests.
references/cache-examples.md
- :精选自Spring Framework参考指南的内容(官方)。
references/spring-framework-cache-docs.md - :从Spring文档中提取的叙述性概述。
references/spring-cache-doc-snippet.md - :注解参数、依赖矩阵、属性目录。
references/cache-core-reference.md - :带测试的端到端示例。
references/cache-examples.md
Best Practices
最佳实践
- Prefer constructor injection and immutable DTOs for cache entries.
- Separate cache names per aggregate (,
users) to simplify eviction.orders - Log cache hits/misses only at debug to avoid noise; push metrics via Micrometer.
- Tune TTLs based on data staleness tolerance; document rationale in code.
- Guard caches that store PII or credentials with encryption or avoid caching.
- Align cache eviction with transactional boundaries to prevent dirty reads.
- 优先使用构造函数注入和不可变DTO作为缓存条目。
- 按聚合根(、
users)划分缓存名称,简化缓存驱逐操作。orders - 仅在debug级别记录缓存命中/未命中情况,避免日志冗余;通过Micrometer推送指标。
- 根据数据陈旧容忍度调整TTL;在代码中记录调整依据。
- 对存储PII或凭证的缓存进行加密,或避免缓存此类数据。
- 使缓存驱逐与事务边界对齐,防止脏读。
Constraints and Warnings
约束与警告
- Avoid caching mutable entities that depend on open persistence contexts.
- Do not mix Spring cache annotations with JCache annotations on the same method.
- Ensure multi-level caches (e.g. Caffeine + Redis) maintain consistency; prefer publish/subscribe invalidation channels.
- Validate serialization compatibility when caching across service instances.
- Monitor memory footprint to prevent OOM when using in-memory stores.
- 避免缓存依赖于持久化上下文的可变实体。
- 不要在同一方法上混合使用Spring缓存注解和JCache注解。
- 确保多级缓存(如Caffeine + Redis)保持一致性;优先使用发布/订阅失效通道。
- 在跨服务实例缓存时,验证序列化兼容性。
- 使用内存存储时,监控内存占用以防止OOM。
Related Skills
相关指南
skills/spring-boot/spring-boot-rest-api-standardsskills/spring-boot/spring-boot-test-patternsskills/junit-test/unit-test-caching
skills/spring-boot/spring-boot-rest-api-standardsskills/spring-boot/spring-boot-test-patternsskills/junit-test/unit-test-caching