Card 02/ 07
@Cacheable vs @CachePut vs @CacheEvict
Skip the method, always run it and refresh the cache, or remove what the cache holds.
Spring has three caching annotations, and each gives the method a different relationship with the cache. @Cacheable may skip the method and return the stored result, @CachePut always runs it and stores the result, and @CacheEvict removes an entry. They share the same cache names and keys, which is how they work on the same entries.
updateFare and evictFare work on the same fares cache that lookupFare(String zone), a @Cacheable method, reads:
@CachePut(value = "fares", key = "#zone")
double updateFare(String zone, double newFare) {
// always runs, then overwrites the cache entry with the result
return newFare;
}
@CacheEvict(value = "fares", key = "#zone")
void evictFare(String zone) {
// removes the entry; nothing to return
}@CachePut always ran (count=1), lookupFare now returns cached: 15.0
after @CacheEvict, lookupFare ran again: 1 time(s)| Annotation | Does |
|---|---|
@Cacheable | Skips the method if the cache already has an entry for these arguments |
@CachePut | Always runs the method, then stores the result; it never skips |
@CacheEvict | Removes an entry, so the next @Cacheable call has to run for real |
The decision rule. Use @Cacheable for reads you are willing to skip. Use @CachePut for a write that should also refresh what a read will see, such as updating a fare and storing the new value in one call. Use @CacheEvict for a write that should only invalidate what is there, when there is nothing to put back yet.
← → move through sections and cards