The use of @cacheable in spring

Source: Internet
Author: User

In spring, the way to read data with the memcached server is achieved by acquiring memcachedclient. However, in the actual development, we often through the spring @cacheable to achieve the data cache, so this article gives you a detailed introduction of @cacheable usage. First of all, before using @cacheable, we need to prepare for the job.

The first step: to import the appropriate jar package.
<classpathentry kind= "Lib" path= "Lib/spring-core-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-cache-1.0.10.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-context-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-beans-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/commons-logging-1.2.jar"/>
<classpathentry kind= "Lib" path= "Lib/log4j-1.2.17.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-expression-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/java_memcached-release_2.0.1.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-aop-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-aspects-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-context-support-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/spring-tx-4.1.4.release.jar"/>
<classpathentry kind= "Lib" path= "Lib/aopalliance-1.0.jar"/>
<classpathentry kind= "Lib" path= "Lib/ognl-3.0.6.jar"/>
<classpathentry kind= "Lib" path= "Lib/trafficcounter-1.0.2.jar"/>
<classpathentry kind= "Lib" path= "Lib/aspectjweaver-1.8.4.jar"/>
<classpathentry kind= "Lib" path= "Lib/javassist-3.11.0.ga.jar"/>

Step Two: Add namespaces to the XML file.

<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:jee= "Http://www.springframework.org/schema/jee"Xmlns:tx= "Http://www.springframework.org/schema/tx"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/conte Xt/spring-context-3.0.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/sp Ring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3 .0.xsd ">

Step three: Add the automatic scanning function.

<base-package= "service"/><   Proxy-target-class= "true"/>

Fourth step: Increase the cache management class.

<BeanID= "Memcacheprovider"class= "Com.springcache.memcache.MemCacheProvider">        < Propertyname= "MemCache"ref= "Memcacheclient"/></Bean><BeanID= "CacheManager"class= "Com.springcache.CacheManager">        < Propertyname= "Elparsername"value= "OGNL"/>        < Propertyname= "Cacheproviders">        <Map>        <entryKey= "Remote"Value-ref= "Memcacheprovider"></entry>        </Map>        </ Property></Bean>

Fifth step: Build a Test class.

Package Service;import Org.springframework.stereotype.service;import com.springcache.annotation.cacheable;@ Service@cacheablepublic class Memcachedservice {    @Cacheable (name = "Remote", key = "' user_name_ ' + #args [0]", expire = Public    string Storeusername (String accountId, string name)    {        return name;    }    @Cacheable (name = "Remote", expire =) public    String storeuseraddress (String accountId, string address)    {        return address;    }}

The @Cacheable supports several parameters:
Key: The cached key, which is empty by default, represents both the parameter type of the method used and the parameter value as key, which supports Spel. For example: memcachedservice.storeuseraddress ("User", "Beijing");
So the corresponding key is: service. Memcachedservice-storeuseraddress_user_beijing
Name: storage location. In the original, remote indicates the use of the memcached server.
Condition: Trigger conditions, only if the condition is satisfied to join the cache, the default is empty, both means that all are added to the cache, support Spel.
Expire: The expiration time, in seconds.

Extension: Using Spring4.3 to solve the problem of multi-threaded concurrent access to the database after cache expiration

After the cache expires, if more than one thread requests access to a data at the same time, it will go to the database simultaneously, resulting in a sudden increase in the database load. Spring4.3 provides a new parameter "Sync" (boolean type, default = False) for @cacheable annotations.

When set to True, only one thread of the request goes to the database, and the other threads wait until the cache is available. This setting can reduce the instantaneous concurrent access to the database.

However, this configuration is not necessarily supported by all cache systems. Verified, guava cache is a supported reference: http://blog.csdn.net/clementad/article/details/51250472

@Service Public classUserservicecacheablesimplImplementsuserservicecacheables{Private Final StaticLogger Logger = Loggerfactory.getlogger (Userservicecacheablesimpl.class);            @Autowired Userdao Userdao; @Override @Cacheable (value  = "Getphonenobyuserid", Sync=true)       PublicString Getphonenobyuserid (intuserId) {Logger.debug ("Getting data from Database, userid={}", userId); returnUserdao.getphonenobyuserid (userId); }  }  


finally , when performing a method that is annotated by @cacheable, spring first checks whether the condition condition is satisfied, if it is not satisfied, executes the method, returns, or, if satisfied, In the cache space named by name, look for an object stored using key, if found, returns the found result, and if no execution method is found, the return value of the method is saved as a Key-value object in the name cache, and then the method returns.

The use of @cacheable in spring

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.