Card 01/ 07
Spring Caching: @EnableCaching and @Cacheable
Three calls with the same argument, and the expensive method body runs only once.
A cache stores the result of a piece of work so that the same request can be answered again without repeating it. In Spring, @EnableCaching switches caching on for the application, and @Cacheable on a method tells Spring to look in a named cache before running the method.
lookupFare does real work: in a production version, a database query or a call to a pricing service. Called three times with the same zone, the work only needs to happen once:
@EnableCaching
@SpringBootApplication
public class RideServiceApplication { }
@Service
class FareLookupService {
@Cacheable("fares")
double lookupFare(String zone) {
// the real work: a query, a call to a pricing service
return computeFare(zone);
}
}3 calls to lookupFare(downtown), method actually ran: 1 time(s)Before the method runs, Spring checks the fares cache for an entry matching this call's arguments. The first call finds nothing, runs the method, and stores the result. The second and third find the stored value and return it, and the method body never executes.
Caching works through the same kind of proxy as transactions, a wrapper object Spring puts in front of the bean, so the same limit applies: a call to lookupFare from inside FareLookupService itself bypasses the cache entirely.
So @Cacheable suits a method whose result depends only on its arguments and changes rarely. For anything else, the question is how the cached value will be kept up to date.
← → move through sections and cards