Sub topic 3
Configuring Caffeine for a Local Cache
Assume you know basic Spring Boot, dependency injection, Maven or Gradle, and application.properties. Caching stores a method result so later calls can avoid a slower database or remote service.
Caffeine for a local cache
Caffeine stores entries in the memory of one application instance. Add spring-boot-starter-cache and Caffeine, then enable caching:
@SpringBootApplication
@EnableCaching
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}Configure a bounded cache with expiration and statistics:
spring.cache.type=caffeine
spring.cache.cache-names=products
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStatsmaximumSize limits memory use. expireAfterWrite removes an entry after it has existed for the specified time.
Redis for a shared cache
Caffeine is local, so each application instance has different entries. Redis is a shared cache that lets multiple instances read the same data.
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
spring.cache.redis.cache-null-values=false
spring.cache.redis.key-prefix=shop::
spring.cache.redis.use-key-prefix=trueUse Redis when shared state matters more than the extra network call. Use Caffeine when low latency and simple deployment matter more.
Expiration, concurrent misses, and testing
Expiration limits staleness. Eviction also occurs when a cache reaches its size limit. Choose values based on data freshness and memory limits.
If many requests miss the same key simultaneously, sync = true asks the cache to coordinate the load:
@Cacheable(cacheNames = "products", key = "#id", sync = true)
public Product findById(Long id) {
return repository.findById(id).orElse(null);
}Test the behavior through the Spring proxy and inspect the CacheManager:
service.findById(1L);
assertThat(cacheManager.getCache("products").get(1L)).isNotNull();Monitoring and pitfalls
Expose cache endpoints and record statistics:
management.endpoints.web.exposure.include=health,caches,metricsInspect /actuator/caches and cache hit or miss metrics. Caffeine statistics require recordStats.
Common problems include stale values, mutable cached objects, cached nulls, and unbounded memory. Pair writes with @CachePut or @CacheEvict, avoid mutating returned cached objects, and define size and expiration limits.
Exercise
When should you choose Redis instead of Caffeine?
Show answer
Choose Redis when multiple application instances must share cached entries or when cache contents must survive an instance restart.