Performance: @CacheEvict for invalidation
This affects how quickly updated data is reflected in the application by controlling cache freshness and memory usage.
@CacheEvict(value = "items", key = "#item.id") public void updateItem(Item item) { // update logic }
@CacheEvict(value = "items", allEntries = true)
public void updateItem(Item item) {
// update logic
}| Pattern | Cache Entries Evicted | Cache Misses | CPU Load | Verdict |
|---|---|---|---|---|
| Evict all entries on update | All | High | High | [X] Bad |
| Evict specific entry by key | One | Low | Low | [OK] Good |
@CacheEvict annotation in Spring Boot?@CacheEvict to clear a cache named "users" after a method executes?cacheNames or value. To clear all entries, use allEntries = true.@CacheEvict(cacheNames = "users", allEntries = true), which is valid syntax.@CacheEvict(cacheNames = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
What happens when deleteProduct(5L) is called?cacheNames = "products" and key = "#id", so it targets the cache entry with the given id.@CacheEvict(cacheNames = "orders", key = "#order.id")
public void cancelOrder(Order order) {
orderRepository.delete(order);
}
Why might the cache eviction not work as expected?#order.id accesses the id property of the 'order' parameter. This requires 'order' to be non-null and have a valid id.#order.id requires the 'order' object to be non-null and have a valid id -> Option C@CacheEvict usage correctly achieves this in the deleteUser method?
public void deleteUser(Long userId) {
userRepository.deleteById(userId);
// cache eviction here
}Pass the test and this pattern moves unknown