Card 01/ 07
All 7 cards
ConceptDifficulty: Intermediate1 min
Checking the Cache Before Running the Method
lookupFare runs some real work — in a production version, a database query or a call to a pricing service. Called three times with the same argument, the work happens 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)@EnableCaching turns the mechanism on for the application; @Cacheable("fares") marks one method to use it, naming which cache it belongs to. Before the method runs, Spring checks the named cache for this call's arguments — found, it returns the stored value and the method body never executes at all.