Expire Cache in Spring Boot: Configure Redis Cache Expiration with Annotations
Efficient cache management is crucial for high-performance Spring Boot applications. When using Redis as your caching layer, controlling cache expiration ensures you serve fresh data, avoid stale responses, and optimize memory use. In this post, you'll learn how to configure expiration policies for cached data in Redis using Spring Boot annotations and configuration.
Why Set Expiration for Redis Cache?
- Data Freshness: Prevents serving outdated information to users.
- Memory Efficiency: Frees up Redis memory by removing unused or stale entries.
- Performance Optimization: Reduces unnecessary database hits while keeping cache relevant.
Configuring Cache Expiration in Spring Boot
1. Set Default Expiration with application.properties
Spring Boot allows you to define a global expiration for all Redis cache entries using the spring.cache.redis.time-to-live
property:
spring.cache.redis.time-to-live=600s
This sets the TTL (Time-To-Live) for all cache entries to 10 minutes.
2. Fine-Grained Expiration with RedisCacheManager
For more control, configure a RedisCacheManager
bean to set different expiration times per cache:
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)); // Default TTL
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
cacheConfigurations.put("users", RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)));
cacheConfigurations.put("products", RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(2)));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigurations)
.build();
}
}
With this setup, the users
cache expires after 5 minutes, while products
expires after 2 minutes.
3. Using Annotations for Caching
Once your cache manager is configured, simply use caching annotations as usual:
@Cacheable(value = "users", key = "#userId")
public User getUserById(Long userId) {
// fetch user logic
}
The expiration policy for the users
cache will be applied automatically based on your configuration.
Best Practices for Cache Expiry
- Choose TTL Wisely: Set TTLs long enough to benefit from caching, but short enough to avoid serving stale data.
- Per-Cache TTLs: Use different TTLs for different data types based on their update frequency and business requirements.
- Monitor Cache Performance: Regularly review cache hit/miss ratios and adjust TTLs as needed.
Conclusion
Configuring expiration policies for Redis cache in Spring Boot is straightforward and highly effective. By leveraging properties, custom cache managers, and annotations, you ensure your application serves fresh, consistent, and performant data—while keeping your Redis instance efficient.