spring-boot-cache
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
Implementation Workflow
实现工作流
1. Define Cache Strategy
1. 定义缓存策略
- Map hot-path read operations to .
@Cacheable - Use on write paths that must refresh cache entries.
@CachePut - Apply (
@CacheEvictwhen invalidating derived caches).allEntries = true - Combine operations with to keep multi-cache updates consistent.
@Caching
- 将热点读操作映射到。
@Cacheable - 在必须刷新缓存条目的写路径上使用。
@CachePut - 应用(当失效衍生缓存时设置
@CacheEvict)。allEntries = true - 结合注解来保持多缓存更新的一致性。
@Caching
2. Shape Cache Keys and Conditions
2. 设计缓存键与条件
- Generate deterministic keys via SpEL (e.g. ).
key = "#user.id" - Guard caching with for selective caching.
condition = "#price > 0" - Prevent null or stale values with .
unless = "#result == null" - Synchronize concurrent updates via when needed.
sync = true
- 通过SpEL生成确定性的键(例如)。
key = "#user.id" - 使用来实现选择性缓存。
condition = "#price > 0" - 通过避免缓存空值或过期值。
unless = "#result == null" - 必要时通过同步并发更新。
sync = true
3. Manage Providers and TTLs
3. 管理提供商与TTL
- Configure provider-specific options:
- Caffeine spec:
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m - Redis TTL:
spring.cache.redis.time-to-live=600000 - Ehcache XML: define and heap/off-heap resources.
ttl
- Caffeine spec:
- Expose cache names via .
spring.cache.cache-names=users,orders,catalog - Avoid on-demand cache name creation in production unless metrics cover usage.
- 配置提供商特定的选项:
- Caffeine 规格:
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m - Redis TTL:
spring.cache.redis.time-to-live=600000 - Ehcache XML:定义以及堆/堆外资源。
ttl
- Caffeine 规格:
- 通过暴露缓存名称。
spring.cache.cache-names=users,orders,catalog - 生产环境中避免按需创建缓存名称,除非有指标覆盖其使用情况。
4. Operate and Observe Caches
4. 操作与观测缓存
- Surface cache maintenance via a dedicated with programmatic
CacheManagementServiceaccess.cacheManager.getCache(name) - Schedule periodic eviction for time-bound caches using .
@Scheduled - Wire Actuator endpoint and Micrometer meters to track hit ratio, eviction count, and size.
cache
- 通过专用的提供缓存维护功能,该服务可通过
CacheManagementService以编程方式访问缓存。cacheManager.getCache(name) - 使用为限时缓存调度定期驱逐任务。
@Scheduled - 连接Actuator的端点和Micrometer指标,以跟踪命中率、驱逐次数和缓存大小。
cache
5. Test and Validate
5. 测试与验证
- Prefer slice or unit tests with Mockito/SpyBean to ensure method invocation counts.
- Add integration tests with Testcontainers for Redis/Ehcache when using external providers.
- Validate concurrency behavior under load (e.g. scenarios).
sync = true
- 优先使用Mockito/SpyBean进行切片测试或单元测试,以确保方法调用次数符合预期。
- 当使用外部提供商时,结合Testcontainers为Redis/Ehcache添加集成测试。
- 验证负载下的并发行为(例如场景)。
sync = true
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