Card 06/ 07
Practice: Choosing a Caching Annotation for Each Method
Three methods on one cache: which annotation goes on each, and why.
@Cacheable skips a method when the cache already has the answer, @CachePut always runs and refreshes the cache, and @CacheEvict removes an entry. Choose one for each method below, with a reason, before you open the answer.
RideHistoryService has a method getHistory(riderId) that is expensive and rarely changes, and a method clearHistory(riderId) that deletes a rider's history entirely. Both use the cache named history, keyed by riderId. A third method, renameRider(riderId, name), changes the name shown in the history and returns the updated history.
See the answer
@Cacheable on getHistory, to skip the expensive work when a cached answer exists. @CacheEvict on clearHistory, because after a delete there is nothing to put back, only an entry to remove.
@CachePut would be wrong on clearHistory: it would store whatever the method returns, such as an empty history, instead of making the next read reload.
renameRider suits @CachePut: it changes the history and returns the new version, so storing that result keeps the next read a hit.
← → move through sections and cards