How to manipulate caching by condition
The caching method described earlier, there is no condition that all calls to the Getaccountbyname method of the Accountservice object will be cached, regardless of the value of the parameter, if there is a requirement that only the account name length is less than or equal to 4, the cache will be cached , more than 4 does not use the cache, then how to implement it.
Spring Cache provides a good way to do this, based on the condition definition of the SPEL expression, which is a property of the @Cacheable annotation, which I'll show you in listing 13. Accountservice.java (Getaccountbyname method revision, support conditions)
1 2 3) 4 5 |
@Cacheable (value= "Accountcache", condition= "#userName. Length () <= 4")//cache called Accountcache public account Getaccountbyname (String userName) {//method internal implementation does not take into account the cache logic, the direct implementation of business return Getfromdb (UserName);} |
Note that the condition= "#userName. Length () <=4", where the Spel expression is used to access the length () method of the parameter UserName object, and the conditional expression returns a Boolean value, True/false, when the condition is True to perform a cache operation, otherwise the return result of the method execution is called directly. listing 14. Test Methods
1 2 3 4 |
S.getaccountbyname ("Somebody");//length greater than 4, will not be cached S.getaccountbyname ("SBD"),///length less than 4, will be cached S.getaccountbyname ("Somebody //or query database S.getaccountbyname ("SBD");//will return from the cache |
listing 15. Running Results