Ehcache Learning (iii) Ehcache and SPRINGAOP Interceptor instances

Source: Internet
Author: User
Tags assert throwable

This time we use springaop+ehcache combination to achieve data caching, we can cache system Service or DAO layer Get/find and other methods to return the results, if the data update (using the Create/update/delete method), then Refreshes the corresponding contents in the cache.

The most common in AOP is the interceptor, so the first thing we need to create is an interceptor:

? Methodcacheinterceptor 
<span style= "Font-family:microsoft yahei;font-size:14px;" >public class Methodcacheinterceptor implements Methodinterceptor, Initializingbean {private static final Log Logge    R = Logfactory.getlog (Methodcacheinterceptor.class);    Private cache cache;    public void Setcache (cache cache) {This.cache = cache;    } public Methodcacheinterceptor () {super ();     /** * Public Object Invoke (Methodinvocation invocation), completed the search cache/new Cache function. * @param invocation * @return * @throws throwable * * @Override public Object invoke (Methodinvocation in        Vocation) throws Throwable {String targetName = Invocation.getthis (). GetClass (). GetName ();        String methodName = Invocation.getmethod (). GetName ();        object[] arguments = invocation.getarguments ();        Object result;        Logger.debug ("Find object from Cache is" + cache.getname ());        String CacheKey = Getcachekey (TargetName, methodName, arguments);//The search cache feature, if present, is directly returned, otherwise it will be created after the element element = Cache.get (cacheKey) is stored;            if (element = = null) {Logger.debug ("hold up Method, Get method result and create cache........!");   result = Invocation.proceed ();            The effect of this code is to obtain the return value of the intercepted method element = new Element (CacheKey, (Serializable) result);        Cache.put (Element);    } return Element.getvalue ();//return null; }/** * Implement Initializingbean, check if cache is empty * @throws Exception */@Override public void Afterp Ropertiesset () throws Exception {assert.notnull (cache, "need a cache.    Please use Setcache (Cache) to create it. "); /** * Method of obtaining the cache key, the cache key is the unique identifier of an Element in the cache * The cache key includes the package name + class name + method name, such as Com.co.cache.service.UserS        Erviceimpl.getalluser */private string Getcachekey (String targetName, String methodName, object[] arguments) {        StringBuffer sb = new StringBuffer (); Sb.append (TargetName). APpend (".").        Append (MethodName);                if (arguments! = null) && (arguments.length! = 0)) {for (int i = 0; i < arguments.length; i++) { Sb.append (".").            Append (Arguments[i]);    }} return sb.tostring (); }}</span>
?  Methodcacheafteradvice
<span style= "Font-family:microsoft yahei;font-size:14px;" >public class Methodcacheafteradvice implements Afterreturningadvice, Initializingbean {private static final Log Lo    Gger = Logfactory.getlog (Methodcacheafteradvice.class);    Private cache cache;    public void Setcache (cache cache) {This.cache = cache;    } public Methodcacheafteradvice () {super ();        } @Override public void Afterreturning (object arg0, Method arg1, object[] arg2, Object Arg3) throws Throwable {        String className = Arg3.getclass (). GetName ();        List List = Cache.getkeys ();            for (int i = 0;i<list.size (); i++) {String CacheKey = string.valueof (List.get (i));                if (Cachekey.startswith (ClassName)) {cache.remove (CacheKey);            Logger.debug ("Remove cache" + CacheKey); }}} @Override public void Afterpropertiesset () throws Exception {assert.notnull (cache, "need a C Ache. Please use SetcachE (Cache) create it. ");}} </span>

Subsequently, an interceptor Methodcacheafteradvice is created, which acts as a user Create/update/delete operation to refresh the/remove related cache content, this interceptor implements the Afterreturningadvice interface, will be executed after the intercepted method executes in the

Public void Afterreturning (Object arg0, Method arg1,object[] arg2, Object ARG3) The operation scheduled in the method

? Configuration file: Application_spring_cache.xml
<span style= "Font-family:microsoft yahei;font-size:14px;"       ><?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "http://www.springframework.org/schema/ Context "xmlns:cache=" Http://www.springframework.org/schema/cache "xmlns:mvc=" http://www.springframework.org/ Schema/mvc "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/sc Hema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org /schema/context/spring-context-3.0.xsd Http://www.springframework.org/schema/cache Http://www.springframewor K.org/schema/cache/spring-cache-3.2.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org /schema/mvc/spring-mvc.xsd "> <!--Support cache annotations--<cache:annotation-driven cache-manager=" CacheManager "/> <context:component-scan base-package= "ehcache.*"/> <!--some @requestmapping requests and some conversions---<mvc:annotatio N-driven/> <!--pre-and <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver"     > <property name= "prefix" value= "/"/> <property name= "suffix" value= ". jsp"/> </bean> <!--two ways to access static resources-<!--<mvc:default-servlet-handler/>-<!--<mvc:resources Loc ation= "/*" mapping= "/**"/>--> <mvc:view-controller path= "/" view-name= "forward:/index.jsp"/> <!--Sp The ring's own Java.util.concurrent.ConcurrentHashMap-based cache manager (which is available from Spring3.1)-<!--<bean id= "            CacheManager "class=" Org.springframework.cache.support.SimpleCacheManager "> <property name=" Caches "> <set> <bean name= "Mycache" class= "Org.springframework.cache.concurrent.ConcurrentMapCacheFac Torybean "/> </set> </property> </bean> <!--If you want to use only the buffers provided by spring itself, comment out the following two beans about the Ehcache configuration and enable The Simplecachemanager above--<!--Spring provides Ehcache-based cache Manager--<!--cache Properties--<bean id= "Cach Emanagerfactory "class=" Org.springframework.cache.ehcache.EhCacheManagerFactoryBean "> <property name=" Configlocation "value=" Classpath:/ehcache.xml "/> </bean> <bean id=" CacheManager "class=" Org.springframe Work.cache.ehcache.EhCacheCacheManager "> <property name=" CacheManager "ref=" Cachemanagerfactory "/> &lt ;/bean> <!--in order to test the interceptor cache--<!--define EhCache's factory and set the cache name--and <bean id= "EhCache" class= "used Org.springframework.cache.ehcache.EhCacheFactoryBean "> <property name=" CacheManager "> <ref l Ocal= "Cachemanagerfactory"/> </property> <!--If the name set in the CacheName attribute cannot be found in Ehcache.xml, the Default--<!--cache (dEfaultcache label definition)--<property name= "CacheName" > <value>DEFAULT_CACHE</value>          </property> </bean> <!--find/create cache blocker--<bean id= "Methodcacheinterceptor" Class= "Ehcache.         Cacheinterceptor.methodcacheinterceptor "> <property name=" Cache "> <ref local=" EhCache "/>          </property> </bean> <!--flush cache blocker--<bean id= "Methodcacheafteradvice" Class= "Ehcache.         Cacheinterceptor.methodcacheafteradvice "> <property name=" Cache "> <ref local=" EhCache "/> </property> </bean> <!--The above code eventually created two "Pointcuts", Methodcachepointcut and <!--Methodcachep Ointcutadvice, the method used to intercept different method names, can be arbitrarily increased as needed-<!--the name of the interception method required. --<bean id= "Methodcachepointcut" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor" &G        T <property name= "Advice"; <ref local= "Methodcacheinterceptor"/> </property> <property name= "Patterns" > &L            T;list> <value>.*find.*</value> <value>.*get.*</value> </list> </property> </bean> <bean id= "Methodcachepointcutadvice" class= "org.sp Ringframework.aop.support.RegexpMethodPointcutAdvisor "> <property name=" Advice "> <ref local=                "Methodcacheafteradvice"/> </property> <property name= "Patterns" > <list> <value>.*create.*</value> <value>.*update.*</value> <    value>.*delete.*</value> </list> </property> </bean> <!--method Test-    <!--If the cached configuration and spring interception can be used directly in one method without introduction, otherwise it needs to be introduced--<!--<import resource= "Cachecontext.xml"/>--> <bean ID= "Testservicetarget" class= "Ehcache. Service.testserviceimpl "/> <bean id=" Testservice "class=" Org.springframework.aop.framework.ProxyFactoryBean        "> <property name=" target "> <ref local=" testservicetarget "/> </property> <property name= "Interceptornames" > <list> <value>methodcachepointcut</v alue> <value>methodCachePointCutAdvice</value> </list> </property > </bean></beans></span>
Ehcache.xml
<span style= "Font-family:microsoft yahei;font-size:14px;" ><ehcache xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= ". /config/ehcache.xsd "> <!--when the number of objects in the memory cache exceeds maxelementsinmemory, the cache object is written to the disk cache (requires the object to implement the serialization interface). --<diskstore path= "Java.io.tmpdir"/> <!--: Used to configure the physical path used by the disk cache, the file suffix used by the Ehcache disk cache is *.data and *.index. --<defaultcache maxelementsinmemory= "10000" eternal= "false" timetoidleseconds= "Timetoliveseconds=" maxelementsondisk= "10000000" Diskexpirythreadintervalsecond s= "memorystoreevictionpolicy=" "LRU" > <persistence strategy= "Localtempswap"/&GT;&LT;/DEFAULTCAC He><cache name= "Default_cache" maxelementsinmemory= "10000" eternal= "false" Timetoidles  Econds= "300000" timetoliveseconds= "600000" overflowtodisk= "true"/></ehcache></span>
? Test Cases Interface Testservice
<span style= "Font-family:microsoft yahei;font-size:14px;" >package Ehcache. Iservice;import java.util.list;/** * Created by Xiaona on 2016/6/14. */public interface Testservice {public    List getallobject ();    public void Updateobject (Object object);} </span>
Implement Testserviceimpl
<span style= "Font-family:microsoft yahei;font-size:14px;" >package Ehcache. Service;import Ehcache. Iservice.testservice;import org.springframework.stereotype.service;import java.util.list;/** * Created by Xiaona on 2016/6/14. */@Servicepublic class Testserviceimpl implements Testservice {    @Override public    List getallobject () {        SYSTEM.OUT.PRINTLN ("The element does not exist within the---testservice:cache, find and place it into cache! ");        return null;    }    @Override public    void Updateobject (Object object) {        System.out.println ("---testservice: Updated object, this Class produces the Cache will be removed ");}    } </span>
Method Invocation

Two ways: Getbean mode and read with annotations

The first way:
<span style= "Font-family:microsoft yahei;font-size:14px;" >package Ehcache.controller;import Ehcache. Iservice.testservice;import Org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;/** * Created by Xiaona on 2016/6/14. */public class Testmain {public static void main (string[] args) {ApplicationContext context = new CLASSPATHX        Mlapplicationcontext ("Application_spring_cache.xml");        Testservice testservice= (Testservice) Context.getbean ("Testservice");        System.out.println ("First time to find and create the cache");        Testservice.getallobject ();        System.out.println ("2--Find in Cache");        Testservice.getallobject ();        System.out.println ("3--remove cache");        Testservice.updateobject (NULL);        SYSTEM.OUT.PRINTLN ("4--needs to re-locate and create the cache");    Testservice.getallobject (); }}</span>
The second way:
<span style= "Font-family:microsoft yahei;font-size:14px;" > @Resourceprivate testservice testservice;    @RequestMapping (value = "/testinterceptor", method = requestmethod.get) public    String Testinterceptor () {        System.out.println ("First time to find and create the cache");        Testservice.getallobject ();        System.out.println ("2--Find in Cache");        Testservice.getallobject ();        System.out.println ("3--remove cache");        Testservice.updateobject (null);        SYSTEM.OUT.PRINTLN ("4--needs to re-locate and create the cache");        Testservice.getallobject ();        return root + "/" + "Testinterceptor";    } </span>

The premise is that the Testservice implementation Testserviceimpl must be annotated with @service so that it can be handed over to the container for management. What results indicate that our success is obtained from the cache? can see that

The first step is to execute Getallobject (), execute the method within the Testserviceimpl, and create the cache, and in the second execution of the Getallobject () method, because the cache has the caching of the method, the result of the method is obtained directly from the cache. So did not print out the contents of the Testserviceimpl, and the third step, called the Updateobject method, and Testserviceimpl related to the cache is removed, so in fourth step execution, and then execute Testserviceimpl , create the Cache in the method.

? Summary 

We see that the combination of SPRINGAOP, can achieve our interception of the request method, in fact, many times we use the page is not changed for a certain time, at this time we need to intercept the frequently called method to cache, so that the user can improve the response speed of the page request.

Ehcache Learning (iii) Ehcache and SPRINGAOP Interceptor instances

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.