Spring Cache-@Cacheable

@Cacheable is an annotation that can be applied to both the method level and the class level. Cache management has been implemented through it since spring 3.1.

What can @Cacheable do?
For easy-to-understand understanding, take a chestnut:
a method, getBooksByUsernameAndLanguage(String username, int language), is obviously a method to get all my English book objects in the database, and the return should be a list. If the return value of this function is large and it will be called frequently on the page, then each call must reconnect to the database and return a list with a huge amount of data, which may result in a relatively large page response and resource consumption. And what we hope is that when this method is called for the first time, the returned data can be placed in the server-side cache, so that when this method is called later, it can be directly retrieved from the cache, so that there is no need to check the database occupation. Resources. This is what @Cacheable does.

How to use @Cacheable?
Give a chestnut (I like to code directly, simple and rude):

@Cacheable(value = "CACHE_BOOK",key = "#username", condition = "#language = 1")
public List<Book> getBooksByUsernameAndLanguage(String username, int language) {
    
    
     // balabalabala...里面的代码不重要
     return bookList;
}

Looking at the code, the @Cacheable annotation has only three attributes.

value : required. It is a name that you choose yourself, which indicates where the bookList returned when you call this method for the first time will be stored in memory.

key : Optional. To use the SpEL expression, this corresponds to the parameter username. When the value of the incoming username changes, the data in the cache will not be retrieved, but the getBooksByUsernameAndLanguage method will be executed. (This is necessary, because the username changes, the return value also changes, and the data in the cache does not match, so this option is very important). Spring uses the method signature as the key by default.

condition : The bookList returned by the method should be cached? condition adds a qualification. In this example, only the incoming language code is 1, the bookList returned will be cached. If another value is passed to language, then the bookList will not be cached.
Next time you encounter the problem that the data is not updated after the page is refreshed, remember to see if it is @Cacheable.

Supplement: In fact, when the method is called for the second time, Spring will go to the cache to see if there is corresponding data before executing the getBooksByUsernameAndLanguage method. If there is, the method will not be executed. No, just execute.

Reference: Spring
Cache- @Cacheable local caching solution-Caffeine Cache spring cache learning- @Cacheable
usage details

Guess you like

Origin blog.csdn.net/qq_33697094/article/details/109336375