Card 03/ 07
Cache Keys Example: One Entry per Argument
The downtown fare is cached, and asking for the suburb fare still runs the method.
Each cache entry is stored under a key, and by default @Cacheable, the annotation that returns a stored result instead of running the method again, builds the key from the method's arguments. The examples use lookupFare(String zone), marked @Cacheable("fares"), and updateFare(String zone, double newFare), which stores a new fare in the same cache. Different arguments therefore mean different entries: caching lookupFare("downtown") does nothing for lookupFare("suburb").
With the downtown fare already cached, the next call asks for the suburb:
different arg (suburb) after downtown cached, method ran: 1 time(s) for the new keyThe method ran again, because "suburb" is a different key. Here the key is only the String zone; with several arguments, Spring combines all of them into one key.
@CachePut(value = "fares", key = "#zone") on updateFare spells the same key out by hand, in SpEL (Spring's expression language, where #zone means the parameter named zone). It has to, because updateFare takes a second argument, newFare, that must not become part of the key, or the update would be stored where lookupFare never looks.
So the key decides what counts as the same request. Check it whenever a cached method takes more than one argument, or when a write and a read must meet at the same entry.
← → move through sections and cards