Sub topic 7
Keeping the cache consistent with @CachePut and @CacheEvict
This chapter assumes you can already use @Cacheable, know how SpEL cache keys work, and have caching enabled with @EnableCaching. A cache holds a copy of your data. When the source changes, the copy must change too, or readers see stale values. Spring gives you two annotations for this: @CachePut and @CacheEvict.
The write path problem
@Cacheable only helps reads. If update changes a product in the store but the products cache still holds the old object, the next findById returns the old price until the entry expires. You have two ways to fix this: replace the entry with the new value, or remove the entry so the next read reloads it.
@CachePut: replace the entry
@CachePut always runs the method and then stores the return value under the given key. Unlike @Cacheable, it never skips the method.
@CachePut(cacheNames = "products", key = "#product.id()")
public Product update(Product product) {
store.put(product.id(), product);
return product;
}The key must match the key used by findById. Here findById uses #id, a Long, and update uses #product.id(), also a Long. If the two keys differ in value or type, the put creates a second entry and the old one stays stale.
The method must also return the value that readers should see. A void method would cache null.
@CacheEvict: remove the entry
@CacheEvict removes an entry after the method succeeds.
@CacheEvict(cacheNames = "products", key = "#id")
public void delete(Long id) {
store.remove(id);
}Evicting is often safer than putting. The next read loads fresh data from the source, so the cache cannot hold a value that differs from what the database would return, for example when the database fills in a version number or a default.
Two useful attributes:
allEntries = trueclears the whole named cache. Use it after bulk changes, and note that it cannot be combined withkey.beforeInvocation = trueevicts before the method runs, so the entry is removed even if the method throws. By default, a method that throws leaves the cache untouched.
Related caches
Changing a product can make other caches wrong too. The productSearch cache from the previous chapter stores lists built from product names. Updating one product does not refresh those lists. Use @Caching to apply several operations at once.
@Caching(
put = @CachePut(cacheNames = "products", key = "#product.id()"),
evict = @CacheEvict(cacheNames = "productSearch", allEntries = true))
public Product update(Product product) {
store.put(product.id(), product);
return product;
}Choosing between them
| Situation | Better choice | Reason |
|---|---|---|
| Method returns the exact object readers need | `@CachePut` | Saves a reload |
| Stored data may differ from the returned object | `@CacheEvict` | Next read gets the real state |
| Delete | `@CacheEvict` | Nothing remains to cache |
| Many derived entries affected | `@CacheEvict(allEntries = true)` | Hard to update each one |
Do not put @Cacheable and @CachePut on the same method. One skips the method and the other forces it to run, so the behavior is confusing.
Common errors
- Key mismatch between the read and write methods, which leaves stale entries.
- Calling an annotated method from the same class. The proxy is bypassed, so no put or evict happens.
- Eviction inside a database transaction that later rolls back. The entry is already gone, which is harmless, but a put of data that is later rolled back is not.
Exercise
A method annotated with @CacheEvict(cacheNames = "products", key = "#id") throws an exception. Is the entry removed? How would you change that?
Show answer
No. By default eviction happens after the method completes successfully, so an exception leaves the entry in the cache. Set beforeInvocation = true to evict before the method runs.
Exercise
findById is cached with key = "#id", but update uses @CachePut(cacheNames = "products", key = "#product.name()"). What goes wrong?
Show answer
The put stores the product under its name, not its id. The entry under the id key is never refreshed, so findById keeps returning the old object, and the cache also holds a useless extra entry.