spring-boot-cache
giuseppe-trisciuoglio/developer-kit
Configure Spring Boot caching with Redis/Caffeine/EhCache, TTL policies, and @Cacheable/@CacheEvict annotations.
What is spring-boot-cache?
Implements cache abstraction patterns for Spring Boot 3.5+ services using configurable providers (Caffeine, Redis, Ehcache) with TTL and eviction policies. Use when adding caching to reduce database load, configuring cache expiration, evicting stale data, or diagnosing cache behavior via Actuator metrics.
- Configure Caffeine, Redis, or Ehcache cache managers with TTL and capacity policies
- Apply @Cacheable, @CachePut, and @CacheEvict annotations to service methods
- Shape cache keys using SpEL expressions with conditional caching via condition/unless
- Validate cache hits and misses through integration tests and Actuator endpoints
- Expose cache metrics (hit/miss ratios) via /actuator/caches and /actuator/metrics/cache.gets
- Implement eviction strategies and programmatic cache management
How to install spring-boot-cache
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-cache- Spring Boot 3.5 or later
- spring-boot-starter-cache dependency
- One cache provider: caffeine, spring-boot-starter-data-redis, or ehcache starter
- Spring Actuator (optional, for metrics exposure)
How to use spring-boot-cache
- 1.Add spring-boot-starter-cache and your chosen provider (Caffeine/Redis/Ehcache) to pom.xml or build.gradle
- 2.Create a @Configuration class annotated with @EnableCaching and define a CacheManager bean
- 3.Annotate service methods with @Cacheable (reads), @CachePut (writes), or @CacheEvict (deletions)
- 4.Configure TTL and eviction policies via spring.cache.caffeine.spec, spring.cache.redis.time-to-live, or spring.cache.ehcache.config
- 5.Use SpEL in key attributes and condition/unless parameters to shape cache behavior
- 6.Run integration tests to verify cache hits on repeated calls and check /actuator/caches and /actuator/metrics/cache.gets endpoints
Use cases
- Add caching to frequently-accessed data (users, products) to reduce database queries
- Configure multi-level caching (Caffeine + Redis) for distributed Spring Boot services
- Implement selective caching based on data attributes (e.g., cache only expensive products)
- Diagnose cache misses and validate cache invalidation during updates or deletes
- Monitor cache performance and memory usage in production via Actuator metrics
- Spring Boot backend developers building high-throughput services
- Architects designing caching strategies for microservices
- DevOps engineers tuning cache configuration and monitoring metrics
- QA engineers validating cache behavior in integration tests
spring-boot-cache FAQ
@Cacheable checks cache first and only invokes the method on miss; @CachePut always invokes the method and updates the cache; @CacheEvict removes entries from the cache.
Ensure @EnableCaching is on a @Configuration class, the method is public, and it's called from outside the class (Spring uses proxies; self-invocation bypasses caching). Verify the cache manager bean is registered as 'cacheManager'.
Yes, Spring Boot cache abstraction supports caching reactive return types and CompletableFuture values.
Enable Spring Actuator and query /actuator/caches for cache manager registration and /actuator/metrics/cache.gets for hit/miss ratios; push metrics via Micrometer.
No, avoid mixing Spring and JCache annotations on the same method; choose one approach per method for clarity and compatibility.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
name: spring-boot-cache description: "Provides patterns for implementing Spring Boot caching: configures Redis/Caffeine/EhCache providers with TTL and eviction policies, applies @Cacheable/@CacheEvict/@CachePut annotations, validates cache hit/miss behavior, and exposes metrics via Actuator. Use when adding caching to Spring Boot services, configuring cache expiration, evicting stale data, or diagnosing cache misses." allowed-tools: Read, Write, Bash
Spring Boot Cache Abstraction
Overview
6-step workflow for enabling cache abstraction, configuring providers (Caffeine,
Redis, Ehcache), annotating service methods, and validating behavior in
Spring Boot 3.5+ applications. Apply @Cacheable for reads, @CachePut for
writes, @CacheEvict for deletions. Configure TTL/eviction policies and expose
metrics via Actuator.
When to Use
- Add
@Cacheable,@CachePut, or@CacheEvictto service methods. - Configure Caffeine, Redis, or Ehcache with TTL and capacity policies.
- Implement eviction strategies for stale data.
- Diagnose cache misses or invalidation issues.
- Expose hit/miss metrics via Actuator or Micrometer.
Instructions
-
Add dependencies —
spring-boot-starter-cacheplus a provider:- Caffeine:
caffeinestarter - Redis:
spring-boot-starter-data-redis - Ehcache:
ehcachestarter
- Caffeine:
-
Enable caching — annotate a
@Configurationclass with@EnableCachingand define aCacheManagerbean. -
Annotate methods —
@Cacheablefor reads,@CachePutfor writes,@CacheEvictfor deletions. -
Configure TTL/eviction — set
spring.cache.caffeine.spec,spring.cache.redis.time-to-live, orspring.cache.ehcache.config. -
Shape keys — use SpEL in
keyattributes; guard withcondition/unlessfor selective caching. -
Validate setup — run integration test to confirm cache hit on second call; check
GET /actuator/cachesto verify cache manager registration; queryGET /actuator/metrics/cache.getsfor hit/miss ratios.
Examples
Example 1: Basic @Cacheable Usage
@Service
@CacheConfig(cacheNames = "users")
class UserService {
@Cacheable(key = "#id", unless = "#result == null")
User findUser(Long id) { ... }
}
First call → cache miss, repository invoked
Second call → cache hit, repository skipped
Example 2: Conditional Caching with SpEL
@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) { ... }
// Only expensive products are cached
Example 3: Cache Eviction
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) { ... }
For progressive scenarios (basic product cache, multilevel eviction, Redis
integration), load references/cache-examples.md.
Advanced Options
- Use JCache annotations (
@CacheResult,@CacheRemove) for providers favoring JSR-107 interoperability; avoid mixing with Spring annotations on the same method. - Cache reactive return types (
Mono,Flux) orCompletableFuturevalues. - Apply HTTP
CacheControlheaders when exposing cached responses via REST. - Schedule periodic eviction with
@Scheduledfor time-bound caches. - Create a
CacheManagementServicefor programmaticcacheManager.getCache(name).
Troubleshooting
If cache misses persist after adding @Cacheable:
- Verify
@EnableCachingis present on a@Configurationclass. - Confirm the method is public and called from outside the class (Spring uses proxies; self-invocation bypasses the cache).
- Validate SpEL key expressions resolve correctly.
- Confirm the cache manager bean is registered as
cacheManageror explicitly referenced viacacheManager = "myCacheManager".
References
references/spring-framework-cache-docs.md: curated excerpts from Spring Framework Reference Guide.references/spring-cache-doc-snippet.md: narrative overview 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; push metrics via Micrometer.
- Tune TTLs based on data staleness tolerance; document rationale in code.
- Guard caches storing 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.
- Validate serialization compatibility when caching across service instances.
- Monitor memory footprint to prevent OOM with in-memory stores.
- Caffeine + Redis multi-level caches require publish/subscribe invalidation channels.
Related Skills
../spring-boot-rest-api-standards../spring-boot-test-patterns../unit-test-caching
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

spring-boot-crud-patterns
Generate complete CRUD workflows for Spring Boot 3 services with DDD-inspired architecture and REST APIs.

spring-boot-dependency-injection
Constructor-first dependency injection patterns for Spring Boot services and configurations.

spring-boot-event-driven-patterns
Event-Driven Architecture patterns for Spring Boot with domain events, Kafka, and transactional outbox.

spring-boot-openapi-documentation
Generate OpenAPI 3.0 documentation and Swagger UI for Spring Boot 3.x REST APIs with SpringDoc

spring-boot-project-creator
Creates and scaffolds a new Spring Boot project (3.x or 4.x) by downloading from Spring Initializr, generating package structure (DDD or Layered architecture), configuring JPA, SpringDoc OpenAPI, and Docker Compose services (PostgreSQL, Redis, MongoDB). Use when creating a new Java Spring Boot project from scratch, bootstrapping a microservice, or initializing a backend application.

spring-boot-resilience4j
Fault tolerance patterns for Spring Boot 3.x using Resilience4j—circuit breakers, retries, rate limiting, and more.