giuseppe-trisciuoglio/developer-kit

spring-boot-cache

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.

소스 보기
원본 Skill 문서

원본 저장소의 제목, 예시, 코드, 표, 링크, 이미지를 유지해 표시합니다.

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 @CacheEvict to 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

  1. Add dependencies — spring-boot-starter-cache plus a provider:
  • Caffeine: caffeine starter
  • Redis: spring-boot-starter-data-redis
  • Ehcache: ehcache starter
  1. Enable caching — annotate a @Configuration class with @EnableCaching

and define a CacheManager bean.

  1. Annotate methods — @Cacheable for reads, @CachePut for writes,

@CacheEvict for deletions.

  1. Configure TTL/eviction — set spring.cache.caffeine.spec,

spring.cache.redis.time-to-live, or spring.cache.ehcache.config.

  1. Shape keys — use SpEL in key attributes; guard with

condition/unless for selective caching.

  1. Validate setup — run integration test to confirm cache hit on second

call; check GET /actuator/caches to verify cache manager registration; query GET /actuator/metrics/cache.gets for hit/miss ratios.

Examples

Example 1: Basic @Cacheable Usage

java
@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

java
@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) { ... }

// Only expensive products are cached

Example 3: Cache Eviction

java
@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) or CompletableFuture values.
  • Apply HTTP CacheControl headers when exposing cached responses via REST.
  • Schedule periodic eviction with @Scheduled for time-bound caches.
  • Create a CacheManagementService for programmatic cacheManager.getCache(name).

Troubleshooting

If cache misses persist after adding @Cacheable:

  1. Verify @EnableCaching is present on a @Configuration class.
  2. Confirm the method is public and called from outside the class (Spring uses

proxies; self-invocation bypasses the cache).

  1. Validate SpEL key expressions resolve correctly.
  2. Confirm the cache manager bean is registered as cacheManager or explicitly

referenced via cacheManager = "myCacheManager".

References

curated excerpts from Spring Framework Reference Guide.

narrative overview from Spring documentation.

annotation parameters, dependency matrices, property catalogs.

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

같은 저장소의 Skills

더 많은 Skills

모든 Skills
giuseppe-trisciuoglio
커뮤니티

clean-architecture

Provides implementation patterns for Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design in PHP 8.3+ with Symfony 7.x. Use when architecting enterprise PHP applications with entities/value objects/aggregates, refactoring legacy code to modern patterns, implementing domain-driven design with Symfony, or creating testable backends with clear separation of concerns.

설치 수
4
GitHub Stars
359
업데이트
9월 10일
giuseppe-trisciuoglio
커뮤니티

nextjs-authentication

Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js). Use when setting up authentication flows, implementing protected routes, managing sessions in Server Components and Server Actions, configuring OAuth providers, implementing role-based access control, or handling sign-in/sign-out flows in Next.js applications.

설치 수
2
GitHub Stars
358
업데이트
9월 10일
giuseppe-trisciuoglio
커뮤니티

adr-drafting

Creates new Architecture Decision Record (ADR) documents for significant architectural changes using a consistent template and repository-aware naming and storage guidance. Use when a user or agent decides on an architectural change, needs to document technical rationale, or wants to add a new ADR to the project history.

설치 수
1
GitHub Stars
358
업데이트
9월 10일
giuseppe-trisciuoglio
커뮤니티

dynamodb-toolbox-patterns

Provides TypeScript patterns for DynamoDB-Toolbox v2 including schema/table/entity modeling, .build() command workflow, query/scan access patterns, batch and transaction operations, and single-table design with computed keys. Use when implementing type-safe DynamoDB access layers with DynamoDB-Toolbox v2 in TypeScript services or serverless applications.

설치 수
1
GitHub Stars
358
업데이트
9월 10일