Video in progress

How do you give each cache its own TTL in Spring Boot?

In a RedisCacheManagerBuilderCustomizer or your own RedisCacheManager bean, you give each cache name its own RedisCacheConfiguration. If you only need one shared TTL, the spring.cache.redis.time-to-live setting is enough.

📖 Answer

One TTL for everything:

spring:
  cache:
    type: redis
    redis:
      time-to-live: 10m
      key-prefix: "shop:"
      cache-null-values: false

Different TTLs:

@Bean
RedisCacheManagerBuilderCustomizer cacheTtls() {
    var base = RedisCacheConfiguration.defaultCacheConfig()
        .serializeValuesWith(SerializationPair.fromSerializer(
            new GenericJackson2JsonRedisSerializer()));
    return builder -> builder
        .cacheDefaults(base.entryTtl(Duration.ofMinutes(10)))
        .withCacheConfiguration("currency-rates", base.entryTtl(Duration.ofMinutes(1)))
        .withCacheConfiguration("categories", base.entryTtl(Duration.ofHours(6)));
}

The @Cacheable annotation itself has no TTL parameter, and many people in interviews don't know that.

If the TTL depends on the value itself (for example, a token's expiry), Spring Data Redis 3.2+ lets you set a dynamic TTL through RedisCacheWriter.TtlFunction. In earlier versions you'd use RedisTemplate by hand instead of @Cacheable for this.

If you don't set time-to-live, entries live forever and you're left relying on the eviction policy. You almost never want that.