Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use key in Spring @ Cacheable annotations

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use key in Spring @ Cacheable annotations". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Key is used in Spring @ Cacheable annotations

The key property is used to specify the corresponding key when the result of the Spring cache method is returned. This attribute supports SpringEL expressions. When we do not specify this attribute, Spring will generate the key using the default policy. Let's take a look at the custom policy first, and the default policy will be described separately later.

A custom policy means that we can specify our key through Spring's EL expression. The EL expressions here can use method parameters and their corresponding properties. When using method parameters, we can directly use "# parameter name" or "# p parameter index".

Here are several examples of @ Cacheable (value= "users", key= "# id") public User find (Integer id) {returnnull;} @ Cacheable (value= "users", key= "# p0") public User find (Integer id) {returnnull;} @ Cacheable (value= "users", key= "# user.id") public User find (User user) {returnnull @ Cacheable (value= "users", key= "# p0.id") public User find (User user) {returnnull;}

In addition to using the above method parameters as key, Spring also provides us with a root object that can be used to generate key. Through this root object, we can get the following information.

We can also omit "# root" when we want to use the properties of the root object as the key, because Spring uses the properties of the root object by default. Such as:

@ Cacheable (value= {"users", "xxx"}, key= "caches [1] .name") public User find (User user) {returnnull;}

If you want to call a method in the current class

We can also omit "# root" when we want to use the properties of the root object as the key, because Spring uses the properties of the root object by default. Such as:

@ Cacheable (value= {"users", "xxx"}, key= "caches [1] .name") public User find (User user) {returnnull;}

If you want to call a method in the current class

@ Override @ Cacheable (value= {"TeacherAnalysis_public_chart"}, key= "# root.target.getDictTableName () +'_'+ # root.target.getFieldName ()") public List getChartList (Map paramMap) {} public String getDictTableName () {return ";} public String getFieldName () {return";} condition attribute specifies the condition under which it occurs

Sometimes we may not want to cache all the returned results of a method. You can do this through the condition property. The condition property is empty by default, indicating that all invocation scenarios will be cached. Its value is specified by an SpringEL expression, which means caching occurs when it is true; when it is false, it means that no caching processing occurs, that is, the method executes every time the method is called. The following example indicates that caching is performed only if the id of user is even.

@ Cacheable (value= {"users"}, key= "# user.id", condition= "# user.id%2==0") public User find (User user) {System.out.println ("find user by user" + user); return user;} @ CachePut

In an environment that supports Spring Cache, for the method marked with @ Cacheable, Spring checks whether the cache element of the same key exists in the Cache before each execution. If so, the method is no longer executed, but the result is directly obtained from the cache and returned, otherwise it is executed and the returned result is stored in the specified cache. @ CachePut can also declare that a method supports caching. Unlike @ Cacheable, the method using the @ CachePut annotation does not check whether there is a previously executed result in the cache before execution, but executes the method each time and stores the result in the specified cache in the form of a key-value pair.

@ CachePut can also be annotated on classes and methods. When using @ CachePut, we can specify the same properties as @ Cacheable.

@ CachePut ("users") / / executes the method each time and stores the result in the specified cache public User find (Integer id) {return null;} @ CacheEvict

@ CacheEvict is used to annotate methods or classes that need to clear cached elements. When marked on a class, it means that the execution of all methods in it triggers a cache cleanup operation. The properties that @ CacheEvict can specify are value, key, condition, allEntries, and beforeInvocation. The semantics of value, key, and condition are similar to the corresponding attributes of @ Cacheable. That is, value indicates the Cache on which the cleanup operation occurred (corresponding to the name of the Cache); key indicates which key needs to be cleared, and if not specified, the key;condition generated by the default policy is used to indicate the conditions under which the purge operation occurs. Let's take a look at the two new properties allEntries and beforeInvocation.

AllEntries attribute

AllEntries is a boolean type that indicates whether all elements in the cache need to be cleared. The default is false, which means it is not needed. When allEntries is specified as true, Spring Cache ignores the specified key. Sometimes we need to Cache all the elements at once, which is more efficient than clearing elements one by one.

@ CacheEvict (value= "users", allEntries=true) public void delete (Integer id) {System.out.println ("delete user by id:" + id);} beforeInvocation attribute

The cleanup operation is triggered by default after the corresponding method executes successfully, that is, the cleanup operation is not triggered if the method fails to return successfully because an exception is thrown. Using beforeInvocation, you can change the time when the cleanup operation is triggered, and when we specify the property value as true, Spring clears the specified element in the cache before calling the method.

@ CacheEvict (value= "users", beforeInvocation=true) public void delete (Integer id) {System.out.println ("delete user by id:" + id);}

In fact, in addition to using @ CacheEvict to clear cache elements, when we use Ehcache as the implementation, we can also configure Ehcache's own drive policy, which is specified through Ehcache's configuration file. Since Ehcache is not the focus of this article, I won't dwell on it here. For more information about Ehcache, please see my column on Ehcache.

@ Caching

The @ Caching annotation allows us to specify multiple Spring Cache-related annotations on a method or class at the same time. It has three properties: cacheable, put, and evict, which specify @ Cacheable, @ CachePut, and @ CacheEvict, respectively.

@ Caching (cacheable = @ Cacheable ("users"), evict = {@ CacheEvict ("cache2"), @ CacheEvict (value = "cache3", allEntries = true)}) public User find (Integer id) {return null;} use custom annotations

Spring allows us to use custom annotations when configuring cacheable methods, provided that custom annotations must be annotated with corresponding annotations. For example, we have a custom annotation marked with @ Cacheable as follows.

Target ({ElementType.TYPE, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Cacheable (value= "users") public @ interface MyCacheable {}

Then using @ MyCacheable to mark the methods we need to cache can also achieve the same effect.

@ MyCacheable public User findById (Integer id) {System.out.println ("find user by id:" + id); User user = new User (); user.setId (id); user.setName ("Name" + id); return user } @ Cacheable splicing key@Cacheable (value = "page_user", key = "T (String) .valueof (# page) .concat ('-') .concat (# pageSize)", unless = "# result=null") / / since page is int, concat requires that the variable must be String, so turn @ Overridepublic List page (int page, int pageSize) {return userMapper.page (page,pageSize) } the content of "how to use key in the Spring @ Cacheable annotations" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report