cache_patterns

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
      端点(若已启用)的命中/未命中计数器。

🔄 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 (
    allEntries=true
    opsiyonunu değerlendir).
  • @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:
    cache
    endpoint'i üzerinden hit/miss oranlarını izle.
  • Integration Testing:
    @SpringBootTest
    ile cache izolasyonunu ve tutarlılığını test et.
  • TTL/驱逐:配置数据新鲜度(TTL)和驱逐策略(LRU/LFU)。
  • Actuator审计:通过
    cache
    端点监控命中/未命中比率。
  • 集成测试:使用
    @SpringBootTest
    测试缓存隔离性和一致性。

Kontrol Noktaları

检查点

AşamaDoğrulama
1Transactional 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
    ,
    @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