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

Progress is saved in this browser. No account needed.

Tip: pressing Next marks this lesson complete automatically.

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.

Finished reading? Mark this lesson complete to track your progress.

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