Learn / Frameworks / Spring Boot / Caching with Spring Cache

Spring Boot · Lesson 9 of 15

Caching with Spring Cache

@Cacheable, @CacheEvict and a Redis cache manager.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 8: Transactions and Locking

What you will learn

  • Cache a method
  • Evict on write
  • Switch to Redis

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Spring Cache is a set of annotations over a cache manager. Start in-memory, switch to Redis when you have more than one instance.

Annotations

@Configuration
@EnableCaching
public class CacheConfig {}

@Service
public class ProductService {
    @Cacheable("products")
    public ProductDto get(long id) { return repo.findById(id).map(this::toDto).orElseThrow(); }

    @CacheEvict(value = "products", key = "#id")
    public void rename(long id, String name) { ... }
}

Redis

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory f) {
    RedisCacheConfiguration cfg = RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(5));
    return RedisCacheManager.builder(f).cacheDefaults(cfg).build();
}

Cache keys must include everything that changes the result (id, locale, tenant). Evict on every write path, including deletes.

Up next · Lesson 10Actuator, Health and MetricsExpose health, info and Prometheus metrics without leaking internals.