spring– Cache Annotations

Source: Internet
Author: User
Tags aop generator
Spring Cache Abstraction Overview

The spring framework itself does not implement a caching solution, However, starting from 3.1, the Org.springframework.cache.Cache and Org.springframework.cache.CacheManager interfaces are defined, providing a declaration of caching capabilities that can be integrated with a variety of popular cache implementations.

The cache interface is a cached component specification definition that contains the various sets of operations for the cache;

The cache interface Spring provides a variety of Xxxcache implementations: such as Rediscache,ehcachecache, Concurrentmapcache, etc.;

The CacheManager interface is the Cache Manager specification, which is simply used to store cache,spring The default also provides some implementation of the column manager.

Spring Cache Abstraction provides 5 annotations for declaring cache rules:

@Cacheable: The ability to cache results based on the request parameters of a method, used for querying

@CachePut: Execute the method and cache the results

@CacheEvict: Emptying the cache

@Caching: Ability to apply multiple cache annotations simultaneously

@CacheConfig: Public configuration for extracting the cache (class level)

Above 5 annotations In addition to the @cacheconfig annotations are class-level annotations, the remaining 4 annotations can be used on both classes and methods, acting on a class to represent all methods under the class that take effect, only for the method in effect, and only for public-decorated character methods. The method of protected or private modification does not apply.

@Cacheable annotations

The function of the @Cacheable annotation is that spring finds the return value of the method in the cache before calling the method, the default key is generated based on the parameter value, and if present, returns the value in the cache, otherwise executes the method and saves the return value to the cache

@Cacheable Running Process:

1. Before the method is run, go to the cache (cached component) and fetch it according to the name specified by Cachenames;

(CacheManager gets the appropriate cache first), first gets the cache if no cache component is created automatically.

2. Go to the cache to find the cached content, using a key, the default is the parameter value of the method;

Key is generated according to a certain strategy; By default it is generated using Keygenerator.

The default policy that spring loads by default for Simplecachemanage,simplekeygenerator generates key is:

If there are no parameters; key=new Simplekey ()

If there is a parameter: The value of the key= parameter

If there are multiple parameters: Key=new Simplekey (params)

3. Call the target method without checking the cache;

4. Put the results returned by the target method into the cache

@Cacheable Property Description:

1.achenames/value: The property value must be provided, specify the name of the cache component, in which cache the return result of the method is placed, and the way the array is to specify multiple caches;

such as: Cachenames = "Product" or Cachenames = {"Product1", "Product2"}

2.key: Cache data using the key, do not specify the key is the default is to use the value of the method parameter this property value supports Spel expression

3.cacheManager: Specifies the cache manager, or cacheresolver specifies to get the parser

4.condition: Cache If you specify a qualifying condition

5.unless: Negative cache; When the condition specified by unless is true, the return value of the method is not cached; You can get the result to judge

unless = "#result = = NULL"

unless = "#a0 ==2": If the value of the first parameter is 2, the result is not cached;

6.sync: Whether to use asynchronous mode

Examples of Use:

1@Cacheable (cachenames = "Product")//default key is parameter, multiple parameters Simplekey [ARG1,ARG2]2 //@Cacheable (cachenames = "Product", key = "#root. methodname+ ' [' + #id + '] ')3 //@Cacheable (cachenames = "Product", Keygenerator = "Mykeygenerator")4 //@Cacheable (cachenames = "Product", key = "#root. methodname+ ' [' + #id + '] '", condition= "#a0 >10", unless = "#a0 ==11") //The conditional cache satisfies the condition=true cache, and the unless=true does not cache5  PublicProduct Getproductbyid (Long id) {6Product Product =Productmapper.getproductbyid (ID);7 System.out.println (product);8    returnproduct;9 }
Ten //Specify the key property value One@Cacheable (cachenames = "Product", key= "#id")//in the form of "#+ parameter name", use the parameter name directly A //or - //@Cacheable (Cachenames = "Product", key= "#a0")//"#a + parameter position" form - PublicProduct Getproductbyid (LongID) { the xxxx - } -@Cacheable (cachenames = "Product", key= "# Productcondition.productid") - //or + //@Cacheable (cachenames = "Product", key= "#a0. ProductId") - PublicProduct getproduct (product productcondition) { + xxxx A}
Custom Key Generator

In addition to the SPEL expression, you can also customize the key generator by The spring cache module provides a build declaration of the Org.springframework.cache.interceptor.KeyGenerator interface for caching key, so we can customize a Mykeygenerator class and implement the Keygenerator Use the following:

1 @Configuration2  Public classMycacheconfig {3 4@Bean ("Mykeygenerator")5      Publickeygenerator Keygenerator () {6         return NewKeygenerator () {7 8 @Override9              Publicobject Generate (Object target, Method method, Object ... params) {Ten                 returnMethod.getname () + "[" + arrays.aslist (params). ToString () + "]"; One             } A         }; -     } -}

This method is used for testing, there are many kinds of strategies about how to generate the cache key on the Internet.

You only need to modify the key property of the annotation when you use it:

1 @Cacheable (cachenames = "Product", Keygenerator = "Mykeygenerator")
@CachePut

The role of @CachePut annotations is simple: call methods and cache data. @cachePut and @cacheable Two annotations can be used to populate the cache, but with a slightly different use, the execution of the @Cacheable annotation is first found in the cache by pressing key, the presence is returned, does not exist, the target method is executed, and the result of the target method is cached. @cacheput does not check the cache, always executes the target method first, and saves the result of the target method to the cache. In practice, such as when performing to an update operation, you want to update the latest data to the cache, and if the method returns an exception, the logic to save the cache is no longer executed.

@CachePut Property Description

@CachePut annotation properties are similar to @cacheput and do not add additional properties

Examples of Use:

1@CachePut (value= "Product", key = "#result. ProductId", condition = "#result!=null")2  PublicProduct UpdateProduct (product product) {3     intCount =productmapper.updateproduct (product);4System.out.println ("Number of rows affected:" +count);5     if(count>0){6         returnproduct;7}Else{8         return NULL;9     }Ten}
@CacheEvict annotations

The effect of this annotation removes the key-value pairs of the attributes in the cache based on the specified key or the Allentries property value.

@CacheEvict Property Description

The @cacheevict annotation provides two additional properties compared to @cacheable:

    1. Allentries: Indicates whether to empty all cached content, default false, if the value is true to empty all content under the specified Cachenames cache block, if Allentries is specified as true, then Zhidingkey value will be meaningless

    2. Beforeinvocation: Whether to empty the cache before executing the method, the default value is False, if the value is true before the target method is called, the flush cache is executed, false if the target method throws an exception, the empty cache logic is no longer executed

Example:

1 //@CacheEvict (value= "Product", key= "#id")2 //@CacheEvict (value= "Product", Allentries = True)//Clear All caches3@CacheEvict (value= "Product", Allentries =true, beforeinvocation =true)//Clear All caches4  Public BooleanDeleteproductbyid (Long id) {5 Productmapper.deleteproductbyid (ID);6     return true;7}
@Caching annotations

This annotation is a grouping annotation that allows you to apply several other annotations at the same time, which provides 3 properties cacheable,put,evict for combining @cacheable, @CachePut, @CacheEvict three annotations, respectively

Examples of Use:

1 @Caching (2cacheable = {@Cacheable (value= "Product", key= "#productName")},3put = {4@CachePut (value= "Product", key= "#result. ProductId"),5@CachePut (value= "Product", key= "#result. ProductName")6         }7 )8  PublicProduct getproductbyname (String productName) {9 TenProduct Product =Productmapper.getproductbyname (productName); One  A      returnproduct; -}

When @cacheing contains both cacheput annotations and cacheable annotations, the target method is still executed first. (not by @cacheable execution, check cache first, return if present)

@CacheConfig

is a class-level annotation that allows shared cache names, Keygenerator, CacheManager, and Cacheresolver

Example:

1 @Service 2 @CacheConfig (cachenames = "Product")3publicclass  Productservice {4 }

Using the annotation on a class, specifying the value of the Cachenames property, the annotation on the method in the class inherits the property value by default and, if the annotation on the method uses the same property as the @cacheconfig, whichever is the method.

1 @Service2@CacheConfig (cachenames = "Product")3  Public classProductservice {4 @Autowired5     PrivateProductmapper Productmapper;6 7@Cacheable (cachenames = "Product1", key = "#root. methodname+ ' [' + #id + '] '")8      PublicProduct Getproductbyid (Long id) {9Product Product =Productmapper.getproductbyid (ID);Ten System.out.println (product); One        returnproduct; A     } -}

The above @cacheable and @cacheconfig all specify the attribute value Cacaenames, which is actually specified by the method annotation.

The key principle of the

Spring cache abstraction is the use of spring AOP, which implements the caching logic by using facets to get the parameters and return values of methods before and after a method call. One thing to note is that spring AOP implements a call to the target method through a dynamic proxy mechanism, so if the annotation method is called inside a class rather than outside the class, it will cause dynamic agent aging, which causes the annotation to be functional.

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.