Evict Cache in Spring Boot: How to Use @CacheEvict
to Remove Specific Cache Entries
Effective cache management is essential for maintaining both the performance and consistency of your Spring Boot applications. While caching accelerates data retrieval, there are times when you need to remove outdated or invalid data from the cache to ensure users always get the most up-to-date information. This is where Spring's @CacheEvict
annotation comes into play.
Why Evict Cache Entries?
- Cache Consistency: Data in the cache can become stale if the underlying data source changes. Evicting cache entries ensures that users receive fresh and accurate data.
- Memory Optimization: Cache has limited space. Removing unused or outdated entries frees up memory for new data.
- Performance: An oversized cache with irrelevant data can slow down lookups. Eviction helps maintain optimal cache performance.
How @CacheEvict
Works in Spring Boot
Spring’s @CacheEvict
annotation allows you to remove one or more entries from a cache. When a method annotated with @CacheEvict
is called, Spring will remove the cached data associated with the specified cache name and key. This can be triggered after or before the method execution, depending on your configuration.
Key parameters of @CacheEvict
:
value
orcacheNames
: Name of the cache.key
: Key of the cache entry to evict (supports SpEL for dynamic keys).allEntries
: If true, clears all entries in the cache.beforeInvocation
: If true, evicts before the method is executed (default is false, i.e., eviction happens after method execution).
Practical Example: Evicting Cache on Update and Delete
Suppose you have a service that manages tutorials. You cache tutorial lookups by ID for performance, but whenever a tutorial is updated or deleted, you want to ensure the cache is evicted so users always get the latest data.
@Service
public class TutorialService {
@Autowired
private TutorialRepository tutorialRepository;
@Cacheable(value = "tutorial")
public Optional<Tutorial> findById(long id) {
return tutorialRepository.findById(id);
}
@CacheEvict(value = "tutorial", key = "#tutorial.id")
public Tutorial update(Tutorial tutorial) {
return tutorialRepository.save(tutorial);
}
@CacheEvict(value = "tutorial", key = "#id")
public void deleteById(long id) {
tutorialRepository.deleteById(id);
}
}
@Cacheable
: Caches the result offindById
using the tutorial’s ID as the key.@CacheEvict
onupdate
: Removes the cache entry for the updated tutorial.@CacheEvict
ondeleteById
: Removes the cache entry for the deleted tutorial.
Result:
After updating or deleting a tutorial, the next time findById
is called for that ID, the data will be fetched from the database and re-cached, ensuring users get the latest information.
Evicting Multiple or All Entries
To evict all entries in a cache (for example, after a bulk update):
@CacheEvict(value = "tutorial", allEntries = true)
public void clearAllTutorialsCache() {
// Logic to bulk update or delete tutorials
}
This clears the entire "tutorial"
cache, ensuring no stale data remains.
Best Practices
- Use
@CacheEvict
on methods that modify or delete cached data. - Always match the cache key in
@CacheEvict
to the key used in@Cacheable
for precise eviction. - For operations affecting many records, consider using
allEntries = true
. - Annotate your configuration or service class with
@EnableCaching
to activate caching support.
Conclusion
The @CacheEvict
annotation is a powerful tool for maintaining cache consistency and performance in Spring Boot applications. By strategically evicting cache entries when data changes, you ensure your users always receive up-to-date information without sacrificing the benefits of caching.
Add @CacheEvict
to your update and delete methods today to keep your cache—and your users—happy!