Cache plug-in EHCache object Cache (Spring)

Source: Internet
Author: User

Object caching is to add the query data to the cache, the next time you query again directly from the cache, rather than go to the database query.

Object caching is generally for methods, classes, and the combination of spring's AOP objects, method caching is simple. There is a need for cutting programming, using spring Methodinterceptor or using @aspect.

The code is as follows:

 PackageCom.hoo.common.ehcache;Importjava.io.Serializable;ImportNet.sf.ehcache.Cache;Importnet.sf.ehcache.Element;ImportOrg.aopalliance.intercept.MethodInterceptor;Importorg.aopalliance.intercept.MethodInvocation;ImportOrg.apache.log4j.Logger;ImportOrg.springframework.beans.factory.InitializingBean;/*** <b>function:</b> Cache Method Interceptor Core code *@authorHoojo * @createDate 2012-7-2 pm 06:05:34 * @file Methodcacheinterceptor.java * @package Com.hoo.common.ehcache * @proj ECT Ehcache * @blogHttp://blog.csdn.net/IBM_hoojo* @email [email protected] *@version1.0*/ Public classMethodcacheinterceptorImplementsMethodinterceptor, Initializingbean {Private Static FinalLogger log = Logger.getlogger (methodcacheinterceptor.class); Privatecache Cache;  Public voidSetcache (Cache cache) { This. cache =Cache; }      Public voidAfterpropertiesset ()throwsException {log.info (cache+ "A cache is required. Use Setcache (Cache) to provide one. "); }      PublicObject invoke (Methodinvocation invocation)throwsthrowable {String targetName=invocation.getthis (). GetClass (). GetName (); String MethodName=Invocation.getmethod (). GetName (); object[] Arguments=invocation.getarguments ();         Object result; String CacheKey=Getcachekey (TargetName, methodName, arguments); Element element=NULL; synchronized( This) {element=Cache.get (CacheKey); if(element = =NULL) {log.info (CacheKey+ "Add to cache:" +cache.getname ()); //invoke the actual methodresult =invocation.proceed (); Element=NewElement (CacheKey, (Serializable) result);            Cache.put (Element); } Else{log.info (CacheKey+ "Use cache:" +cache.getname ()); }        }        returnElement.getvalue (); }     /*** <b>function:</b> Return specific method full path name parameter *@authorHoojo * @createDate 2012-7-2 pm 06:12:39 *@paramtargetName Full path *@paramMethodName Method Name *@paramArguments Parameters *@returnFull Method name*/    Privatestring Getcachekey (String targetName, String methodName, object[] arguments) {stringbuffer sb=NewStringBuffer (); Sb.append (TargetName). Append ("."). Append (MethodName); if((Arguments! =NULL) && (Arguments.length! = 0)) {             for(inti = 0; i < arguments.length; i++) {sb.append ("."). Append (Arguments[i]); }        }        returnsb.tostring (); }}

The method interceptor here is primarily to intercept the method of the class you want to intercept, and then determine if the method's Classpath + method name + parameter value combination of the cache key exists in the cached caches. If it exists, remove the object from the cache and convert it to the return type we want. If not, add the object returned by the method to the cache. The idea is that the parameters of the current method and the object type of the return value need to be serialized.

We need to add Applicationcontext.xml in the SRC directory to complete the configuration of the Methodcacheinterceptor interceptor, which is the idea of injecting our cache object, which cache to manage the object cache, and then which classes, method to participate in the scanning of the interceptor.

Add the following configuration:

<Context:component-scanBase-package= "Com.hoo.common.interceptor"/>  <!--Configuring the EH cache Manager -<BeanID= "CacheManager"class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> <!--to configure a simple cache factory Bean Object -<BeanID= "Simplecache"class= "Org.springframework.cache.ehcache.EhCacheFactoryBean">    < Propertyname= "CacheManager"ref= "CacheManager" />    <!--using cache configuration in cache affinity Ehcache.xml -    < Propertyname= "CacheName"value= "Mobilecache" /></Bean> <!--Configure a cache interceptor object to handle the specific cache business -<BeanID= "Methodcacheinterceptor"class= "com. Hoo.common.interceptor.MethodCacheInterceptor">    < Propertyname= "Cache"ref= "Simplecache"/></Bean> <!--a Pointcut object participating in the cache (Pointcut object, determining when and where to call the Interceptor) -<BeanID= "Methodcachepointcut"class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor">    <!--Configure Cache AOP Facets -    < Propertyname= "Advice"ref= "Methodcacheinterceptor" />    <!--configure which methods participate in a cache policy -    <!--. Represents any single character # # # + indicates that the previous character matches one or more # # # * Indicates a previous character 0 or more times # # # \escape symbols used by any regular expression -                     <!--. * indicates that the preceding prefix (including the package name) represents the Print method -    < Propertyname= "Patterns">        <List>            <value>com.hoo.rest.*restservice*\.*get.*</value>            <value>com.hoo.rest.*restservice*\.*search.*</value>        </List>    </ Property></Bean>

Add the following cache configuration in Ehcache.xml

<name= "Mobilecache"        maxelementsinmemory= "10000"         Eternal = "false"         overflowtodisk= "true"        timetoidleseconds= "1800"         Timetoliveseconds = "3600"         memorystoreevictionpolicy= "LFU"/>

Cache plug-in EHCache object Cache (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.