Springcache using Notes 002_ note driven Spring cache conditionally query

Source: Internet
Author: User
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
1 2 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.