spring-boot-cache by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-cacheSpring Boot 内置了一个缓存抽象层,它通过注解驱动的缓存将昂贵的服务调用封装起来。该抽象层支持多种缓存提供程序(ConcurrentMap、Caffeine、Redis、Ehcache、JCache),而无需更改业务代码。本技能为在 Spring Boot 3.5+ 服务中启用缓存、管理缓存生命周期和验证行为提供了一个简洁的工作流程。
@Cacheable、@CachePut 或 @CacheEvict 注解。使用诸如 "实现服务缓存"、"配置 CaffeineCacheManager"、"更新时驱逐缓存" 或 "测试 Spring 缓存行为" 等触发短语来加载此技能。
遵循以下步骤在 Spring Boot 应用程序中实现缓存:
在项目依赖中包含 spring-boot-starter-cache 和你首选的缓存提供程序(Caffeine、Redis、Ehcache)。
在 @Configuration 类上添加 ,并为你的缓存提供程序声明 CacheManager bean。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
@EnableCaching在 application.yml 中或通过 CacheManager 定制器 bean 配置缓存名称、TTL 设置和容量限制。
对读操作应用 @Cacheable,对更新操作应用 @CachePut,对失效操作应用 @CacheEvict。使用 @CacheConfig 在类级别定义默认缓存名称。
使用 SpEL 表达式定义缓存键(key = "#user.id")、条件(condition = "#price > 0")和 unless 子句(unless = "#result == null")。
创建计划任务或使用 @CacheEvict 并设置 allEntries=true 来定期清除对时间敏感的缓存。
启用 Actuator 缓存端点以观察命中/未命中率。考虑使用 Micrometer 指标进行生产环境可观测性。
spring-boot-starter-cache;根据需要添加提供程序特定的启动器(spring-boot-starter-data-redis、caffeine、ehcache 等)。添加依赖
<!-- 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>
implementation "org.springframework.boot:spring-boot-starter-cache"
implementation "com.github.ben-manes.caffeine:caffeine"
启用缓存
@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
return new CaffeineCacheManager("users", "orders");
}
}
注解服务方法
@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) { ... }
}
验证行为
cache 端点(如果已启用)的命中/未命中计数器。@Cacheable。@CachePut。@CacheEvict(当使派生缓存失效时使用 allEntries = true)。@Caching 组合操作以保持多缓存更新的一致性。key = "#user.id")。condition = "#price > 0" 进行选择性缓存保护。unless = "#result == null" 防止空值或陈旧值。sync = true 同步并发更新。spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10mspring.cache.redis.time-to-live=600000ttl 和堆/堆外资源。spring.cache.cache-names=users,orders,catalog 暴露缓存名称。CacheManagementService 暴露缓存维护功能,该服务提供对 cacheManager.getCache(name) 的程序化访问。@Scheduled 为有时限的缓存安排定期驱逐。cache 端点和 Micrometer 仪表以跟踪命中率、驱逐计数和大小。sync = true 的场景)。@CacheResult、@CacheRemove)进行互操作时集成 JCache 注解。避免在同一方法上混合使用 Spring 注解。Mono、Flux)或 CompletableFuture 值。Spring 存储已解析的值并在命中时重新订阅;考虑 TTL 与发布者语义的对齐。CacheControl 应用 HTTP 缓存头。@Cacheable 用法输入:
// First call - cache miss, method executes
User user1 = userService.findUser(1L);
// Second call - cache hit, method skipped
User user2 = userService.findUser(1L);
输出:
// First call logs:
Hibernate: select u1_0.id,u1_0.name from users u1_0 where u1_0.id=?
// Second call: No SQL executed (served from cache)
输入:
@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) {
return productRepository.findById(id);
}
// Only expensive products are cached
getProduct(1L, new BigDecimal("50.00")); // Not cached
getProduct(2L, new BigDecimal("150.00")); // Cached
输出:
Cache 'products' contents after operations:
{2=Product(id=2, price=150.00)}
输入:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
deleteUser(1L);
输出:
Cache 'users' entry for key '1' removed
references/cache-examples.md 以获取渐进式场景(基本产品缓存、条件缓存、多级驱逐、Redis 集成)。references/cache-core-reference.md 以获取注解矩阵、配置表和属性示例。references/spring-framework-cache-docs.md:从 Spring Framework 参考指南(官方)中精选的摘录。references/spring-cache-doc-snippet.md:从 Spring 文档中提取的叙述性概述。references/cache-core-reference.md:注解参数、依赖矩阵、属性目录。references/cache-examples.md:包含测试的端到端示例。users、orders)分离缓存名称以简化驱逐。每周安装次数
359
代码仓库
GitHub 星标数
173
首次出现
2026年2月3日
安全审计
已安装于
claude-code282
gemini-cli268
opencode268
codex263
cursor263
github-copilot248
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.
@Cacheable, @CachePut, or @CacheEvict to Spring Boot service methods.Use trigger phrases such as "implement service caching" , "configure CaffeineCacheManager" , "evict caches on update" , or "test Spring cache behavior" to load this skill.
Follow these steps to implement caching in Spring Boot applications:
Include spring-boot-starter-cache and your preferred cache provider (Caffeine, Redis, Ehcache) in the project dependencies.
Add @EnableCaching to a @Configuration class and declare CacheManager bean(s) for your cache providers.
Configure cache names, TTL settings, and capacity limits in application.yml or via CacheManager customizer beans.
Apply @Cacheable for read operations, @CachePut for updates, and @CacheEvict for invalidation. Use @CacheConfig to define default cache names at class level.
Use SpEL expressions to define cache keys (key = "#user.id"), conditions (condition = "#price > 0"), and unless clauses (unless = "#result == null").
Create scheduled jobs or use @CacheEvict with allEntries=true to periodically clear time-sensitive caches.
Enable Actuator cache endpoint to observe hit/miss ratios. Consider Micrometer metrics for production observability.
spring-boot-starter-cache; add provider-specific starters as needed (spring-boot-starter-data-redis, caffeine, ehcache, etc.).Add dependencies
<!-- 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>
implementation "org.springframework.boot:spring-boot-starter-cache"
implementation "com.github.ben-manes.caffeine:caffeine"
Enable caching
@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
return new CaffeineCacheManager("users", "orders");
}
}
Annotate service methods
@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) { ... }
}
@Cacheable.@CachePut on write paths that must refresh cache entries.@CacheEvict (allEntries = true when invalidating derived caches).@Caching to keep multi-cache updates consistent.key = "#user.id").condition = "#price > 0" for selective caching.unless = "#result == null".sync = true when needed.spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10mspring.cache.redis.time-to-live=600000ttl and heap/off-heap resources.spring.cache.cache-names=users,orders,catalog.CacheManagementService with programmatic cacheManager.getCache(name) access.@Scheduled.cache endpoint and Micrometer meters to track hit ratio, eviction count, and size.sync = true scenarios).@CacheResult, @CacheRemove). Avoid mixing with Spring annotations on the same method.Mono, Flux) or CompletableFuture values. Spring stores resolved values and resubscribes on hits; consider TTL alignment with publisher semantics.CacheControl when exposing cached responses via REST.@Cacheable UsageInput:
// First call - cache miss, method executes
User user1 = userService.findUser(1L);
// Second call - cache hit, method skipped
User user2 = userService.findUser(1L);
Output:
// First call logs:
Hibernate: select u1_0.id,u1_0.name from users u1_0 where u1_0.id=?
// Second call: No SQL executed (served from cache)
Input:
@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) {
return productRepository.findById(id);
}
// Only expensive products are cached
getProduct(1L, new BigDecimal("50.00")); // Not cached
getProduct(2L, new BigDecimal("150.00")); // Cached
Output:
Cache 'products' contents after operations:
{2=Product(id=2, price=150.00)}
Input:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
deleteUser(1L);
Output:
Cache 'users' entry for key '1' removed
references/cache-examples.md for progressive scenarios (basic product cache, conditional caching, multilevel eviction, Redis integration).references/cache-core-reference.md for annotation matrices, configuration tables, and property samples.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.users, orders) to simplify eviction.Weekly Installs
359
Repository
GitHub Stars
173
First Seen
Feb 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code282
gemini-cli268
opencode268
codex263
cursor263
github-copilot248
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
竞争对手研究指南:SEO、内容、反向链接与定价分析工具
231 周安装
Azure 工作负载自动升级评估工具 - 支持 Functions、App Service 计划与 SKU 迁移
231 周安装
Kaizen持续改进方法论:软件开发中的渐进式优化与防错设计实践指南
231 周安装
软件UI/UX设计指南:以用户为中心的设计原则、WCAG可访问性与平台规范
231 周安装
Apify 网络爬虫和自动化平台 - 无需编码抓取亚马逊、谷歌、领英等网站数据
231 周安装
llama.cpp 中文指南:纯 C/C++ LLM 推理,CPU/非 NVIDIA 硬件优化部署
231 周安装
Verify behavior
cache endpoint (if enabled) for hit/miss counters.