spring-boot-cache

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring 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
    ,
    @CachePut
    , or
    @CacheEvict
    to Spring Boot service methods.
  • 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
    spring-boot-starter-cache
    ; add provider-specific starters as needed (
    spring-boot-starter-data-redis
    ,
    caffeine
    ,
    ehcache
    , etc.).
  • 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

快速开始

  1. Add dependencies
    xml
    <!-- 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>
    gradle
    implementation "org.springframework.boot:spring-boot-starter-cache"
    implementation "com.github.ben-manes.caffeine:caffeine"
  2. Enable caching
    java
    @Configuration
    @EnableCaching
    class CacheConfig {
        @Bean
        CacheManager cacheManager() {
            return new CaffeineCacheManager("users", "orders");
        }
    }
  3. Annotate service methods
    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) { ... }
    }
  4. Verify behavior
    • Run focused unit tests that call cached methods twice and assert repository invocations.
    • Inspect Actuator
      cache
      endpoint (if enabled) for hit/miss counters.
  1. 添加依赖
    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>
    gradle
    implementation "org.springframework.boot:spring-boot-starter-cache"
    implementation "com.github.ben-manes.caffeine:caffeine"
  2. 启用缓存
    java
    @Configuration
    @EnableCaching
    class CacheConfig {
        @Bean
        CacheManager cacheManager() {
            return new CaffeineCacheManager("users", "orders");
        }
    }
  3. 为服务方法添加注解
    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) { ... }
    }
  4. 验证行为
    • 运行针对性的单元测试,调用缓存方法两次并断言仓库调用次数。
    • 检查Actuator的
      cache
      端点(若已启用)的命中/未命中计数器。

Implementation Workflow

实现工作流

1. Define Cache Strategy

1. 定义缓存策略

  • Map hot-path read operations to
    @Cacheable
    .
  • Use
    @CachePut
    on write paths that must refresh cache entries.
  • Apply
    @CacheEvict
    (
    allEntries = true
    when invalidating derived caches).
  • Combine operations with
    @Caching
    to keep multi-cache updates consistent.
  • 将热点读操作映射到
    @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
    condition = "#price > 0"
    for selective caching.
  • Prevent null or stale values with
    unless = "#result == null"
    .
  • Synchronize concurrent updates via
    sync = true
    when needed.
  • 通过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
      ttl
      and heap/off-heap resources.
  • 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
      以及堆/堆外资源。
  • 通过
    spring.cache.cache-names=users,orders,catalog
    暴露缓存名称。
  • 生产环境中避免按需创建缓存名称,除非有指标覆盖其使用情况。

4. Operate and Observe Caches

4. 操作与观测缓存

  • Surface cache maintenance via a dedicated
    CacheManagementService
    with programmatic
    cacheManager.getCache(name)
    access.
  • Schedule periodic eviction for time-bound caches using
    @Scheduled
    .
  • Wire Actuator
    cache
    endpoint and Micrometer meters to track hit ratio, eviction count, and size.
  • 通过专用的
    CacheManagementService
    提供缓存维护功能,该服务可通过
    cacheManager.getCache(name)
    以编程方式访问缓存。
  • 使用
    @Scheduled
    为限时缓存调度定期驱逐任务。
  • 连接Actuator的
    cache
    端点和Micrometer指标,以跟踪命中率、驱逐次数和缓存大小。

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.
    sync = true
    scenarios).
  • 优先使用Mockito/SpyBean进行切片测试或单元测试,以确保方法调用次数符合预期。
  • 当使用外部提供商时,结合Testcontainers为Redis/Ehcache添加集成测试。
  • 验证负载下的并发行为(例如
    sync = true
    场景)。

Advanced Options

高级选项

  • Integrate JCache annotations when interoperating with providers that favor JSR-107 (
    @CacheResult
    ,
    @CacheRemove
    ). Avoid mixing with Spring annotations on the same method.
  • Cache reactive return types (
    Mono
    ,
    Flux
    ) or
    CompletableFuture
    values. Spring stores resolved values and resubscribes on hits; consider TTL alignment with publisher semantics.
  • Apply HTTP caching headers using
    CacheControl
    when exposing cached responses via REST.
  • 当与偏好JSR-107的提供商交互时,集成JCache注解(
    @CacheResult
    @CacheRemove
    )。避免在同一方法上混合使用Spring注解和JCache注解。
  • 缓存响应式返回类型(
    Mono
    Flux
    )或
    CompletableFuture
    值。Spring会存储解析后的值,并在命中时重新订阅;考虑将TTL与发布者语义对齐。
  • 当通过REST暴露缓存响应时,使用
    CacheControl
    设置HTTP缓存头。

Examples

示例

  • Load
    references/cache-examples.md
    for progressive scenarios (basic product cache, conditional caching, multilevel eviction, Redis integration).
  • Load
    references/cache-core-reference.md
    for annotation matrices, configuration tables, and property samples.
  • 加载
    references/cache-examples.md
    查看进阶场景(基础产品缓存、条件缓存、多级驱逐、Redis集成)。
  • 加载
    references/cache-core-reference.md
    查看注解矩阵、配置表和属性示例。

References

参考资料

  • references/spring-framework-cache-docs.md
    : curated excerpts from the Spring Framework Reference Guide (official).
  • references/spring-cache-doc-snippet.md
    : narrative overview extracted from Spring documentation.
  • references/cache-core-reference.md
    : annotation parameters, dependency matrices, property catalogs.
  • references/cache-examples.md
    : end-to-end examples with tests.
  • references/spring-framework-cache-docs.md
    :Spring Framework参考指南的精选摘录(官方)。
  • references/spring-cache-doc-snippet.md
    :从Spring文档中提取的叙述性概述。
  • 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
    ,
    orders
    ) to simplify eviction.
  • 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-standards
  • skills/spring-boot/spring-boot-test-patterns
  • skills/junit-test/unit-test-caching
  • skills/spring-boot/spring-boot-rest-api-standards
  • skills/spring-boot/spring-boot-test-patterns
  • skills/junit-test/unit-test-caching