Card 01/ 07

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.

java
@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);
    }
}
text
3 calls to lookupFare(downtown), method actually ran: 1 time(s)
run in a container — the second and third calls never touch the method body

@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.