Synthèse automatique
Ce skill décrit comment activer et exploiter l'abstraction de cache de Spring Boot : annotations, gestionnaires de cache (Caffeine, Redis, JCache), stratégies d'éviction et supervision.
Points forts
- Déroulé en sept étapes couvrant dépendances, @EnableCaching, configuration, annotations, clés SpEL, éviction et monitoring.
- Extraits de code concrets en Maven et Gradle (starter cache, Caffeine, CaffeineCacheManager).
- Montre comment changer de fournisseur de cache sans toucher au code métier.
- Insiste sur les points sensibles : clés SpEL, clauses condition/unless, invalidation planifiée.
Limites
- La configuration Redis ou Ehcache n'est traitée qu'au niveau des starters, sans exemple détaillé.
- Suppose Java 17+ et Spring Boot 3.5.x ; rien n'est prévu pour les versions antérieures.
- Ne fournit pas de test automatisé complet pour valider le comportement du cache.
À utiliser lorsqu'on ajoute, configure ou débogue du cache applicatif dans un service Spring Boot.
À éviter pour du cache HTTP/CDN, des problématiques de cache distribué avancé (cohérence, sharding) ou un projet hors Spring Boot.
Analyse de sécurité
SûrThe skill provides declarative configuration and code patterns for Spring caching. It declares Read/Write/Bash but contains no destructive, exfiltration, or obfuscation instructions; Bash is only implied for normal build/test activities.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Add Spring Cache to my OrderService: annotate findOrder with @Cacheable, refreshOrder with @CachePut and cancelOrder with @CacheEvict, using the order id as the cache key and skipping null results.Configure a CaffeineCacheManager in my Spring Boot 3.5 app with caches named users and orders, a 10-minute TTL and a 500-entry maximum size, in application.yml.My @CacheEvict on updateUser isn't clearing the users cache — review my SpEL key expressions and beforeInvocation setting and tell me what's wrong.name: spring-boot-cache description: Provides patterns for enabling and operating the Spring Cache abstraction in Spring Boot. Use when implementing application-level caching for performance-sensitive workloads. allowed-tools: Read, Write, Bash
Spring Boot Cache Abstraction
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.
When to Use
- Add
@Cacheable,@CachePut, or@CacheEvictto 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.
Instructions
Follow these steps to implement caching in Spring Boot applications:
1. Add Cache Dependencies
Include spring-boot-starter-cache and your preferred cache provider (Caffeine, Redis, Ehcache) in the project dependencies.
2. Enable Caching
Add @EnableCaching to a @Configuration class and declare CacheManager bean(s) for your cache providers.
3. Define Cache Configuration
Configure cache names, TTL settings, and capacity limits in application.yml or via CacheManager customizer beans.
4. Anotate Service Methods
Apply @Cacheable for read operations, @CachePut for updates, and @CacheEvict for invalidation. Use @CacheConfig to define default cache names at class level.
5. Configure Cache Keys and Conditions
Use SpEL expressions to define cache keys (key = "#user.id"), conditions (condition = "#price > 0"), and unless clauses (unless = "#result == null").
6. Implement Cache Eviction Strategy
Create scheduled jobs or use @CacheEvict with allEntries=true to periodically clear time-sensitive caches.
7. Monitor Cache Performance
Enable Actuator cache endpoint to observe hit/miss ratios. Consider Micrometer metrics for production observability.
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.
Quick Start
-
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) { ... } } -
Verify behavior
- Run focused unit tests that call cached methods twice and assert repository invocations.
- Inspect Actuator
cacheendpoint (if enabled) for hit/miss counters.
Implementation Workflow
1. Define Cache Strategy
- Map hot-path read operations to
@Cacheable. - Use
@CachePuton write paths that must refresh cache entries. - Apply
@CacheEvict(allEntries = truewhen invalidating derived caches). - Combine operations with
@Cachingto keep multi-cache updates consistent.
2. Shape Cache Keys and Conditions
- 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 = truewhen needed.
3. Manage Providers and TTLs
- 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
ttland heap/off-heap resources.
- 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.
4. Operate and Observe Caches
- Surface cache maintenance via a dedicated
CacheManagementServicewith programmaticcacheManager.getCache(name)access. - Schedule periodic eviction for time-bound caches using
@Scheduled. - Wire Actuator
cacheendpoint and Micrometer meters to track hit ratio, eviction count, and size.
5. Test and Validate
- 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 = truescenarios).
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) orCompletableFuturevalues. Spring stores resolved values and resubscribes on hits; consider TTL alignment with publisher semantics. - Apply HTTP caching headers using
CacheControlwhen exposing cached responses via REST.
Examples
Example 1: Basic @Cacheable Usage
Input:
// 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)
Example 2: Conditional Caching with SpEL
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)}
Example 3: Cache Eviction
Input:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
deleteUser(1L);
Output:
Cache 'users' entry for key '1' removed
- Load
references/cache-examples.mdfor progressive scenarios (basic product cache, conditional caching, multilevel eviction, Redis integration). - Load
references/cache-core-reference.mdfor annotation matrices, configuration tables, and property samples.
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.
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.
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.
Related Skills
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/spring-boot-cache-abstraction-mrwakcam/download' --output '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md.part' && mv '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md.part' '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Bash
Extrait original : 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.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.claude/skills/spring-boot-cache'Cursor
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.cursor/skills/spring-boot-cache'Codex
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.agents/skills/spring-boot-cache'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/spring-boot-cache-abstraction-mrwakcam'openskills read 'spring-boot-cache-abstraction-mrwakcam'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Bonnes pratiques React Hook Form
Developpement
Maîtrisez React Hook Form : évitez les anti-patterns, gérez les abonnements, et traitez correctement reset, dirty state et entrées contrôlées.
Migration Emotion vers Mantine
Developpement
Migrer les styled-components Emotion vers des composants Mantine avec style props et modules CSS. Pour convertir .styled.tsx ou supprimer les imports @emotion.
Détecteur de dérive de périmètre
Developpement
Analyse les diffs git par rapport à une intention pour détecter la dérive de périmètre, fichiers non liés et PR trop larges, puis suggère de garder, diviser ou justifier.