Video in progress
What is the difference between @CachePut and @CacheEvict?
@CachePut always runs the method and writes the result into the cache, for updates. @CacheEvict removes the entry from the cache, so the value gets reloaded on the next read.
📖 Answer
@CachePut(cacheNames = "products", key = "#result.id")
public ProductDto update(ProductUpdate cmd) { ... }
@CacheEvict(cacheNames = "products", key = "#id")
public void delete(long id) { ... }
@CacheEvict(cacheNames = "products", allEntries = true)
public void reimport() { ... }
The difference from @Cacheable: @CachePut doesn't look at the cache, the method runs anyway.
In practice many teams use @CacheEvict instead of @CachePut on updates too. The reason is that the object @CachePut returns must have the same format as what's in the cache; if update returns a different DTO, the wrong thing ends up in the cache. Evicting is safer: the next read loads the correct data on its own.
allEntries = true needs care in Redis: on a large cache it deletes a lot of keys.
Sign up to mark studied questions and save your progress.