Using Ehcache in spring based on AOP

Source: Internet
Author: User

To continue this article, this introduction to the service layer cache, AOP-based approach to using Ehcache

First, modify the configuration file

Modify Spring-context-ehcache.xml file, add:

<!--ehcache Cache instance--><bean id= "Testcacheinterceptor" class= " Org.springframework.cache.ehcache.EhCacheFactoryBean "> <property name=" CacheManager "ref=" Ehcachemanager "/ > <property name= "cachename" value= "Aoptestdao"/></bean> <!--notification to weave (tangent)--><bean id= "test Cache "Class=" Org.xs.demo1.CacheInterceptor > <!--incoming Ehcache cache instance-<property name= "cache" ref= "TESTCAC Heinterceptor "/></bean> <!--AOP configuration--><aop:config> <!--defining facets--<aop:aspect ref= "Testcache" > <!--definitions Add a tangent to the cache and <aop:pointcut id= "Testaddcache" expression= "Execution (* ORG.XS.D emo1.testdao.get* (..)) " /> <!--definition Surround notifications-<aop:around pointcut-ref= "Testaddcache" method= "Addcache"/> <!-  -Define the point-and-<aop:pointcut id= "Testremovecache" expression= "Execution (* org.xs.demo1.testdao.update* (..)) to remove the cache ||      Execution (* org.xs.demo1.testdao.delete* (..)) "/>  <!--defining post notifications-<aop:after pointcut-ref= "Testremovecache" method= "RemoveCache"/> </aop:aspect& Gt;</aop:config>

You can also add CacheName as "Aoptestdao" to the cache instance configuration in Ehcache-context.xml

Second, increase the cache operation interceptor

Create a new "Cacheinterceptor.java" class under the "Org.xs.demo1" package in the "Src/main/java" code folder:

Package org.xs.demo1; Import Java.io.serializable;import java.util.List; Import Net.sf.ehcache.cache;import net.sf.ehcache.Element; Import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.ProceedingJoinPoint;         /** * Cache Operation Interceptor */public class Cacheinterceptor {/** * Cache instance */private cache cache;      Public Cache GetCache () {return cache;      } public void Setcache (cache cache) {This.cache = cache;        }/** * Increased cache */public Object Addcache (Proceedingjoinpoint joinpoint) {object result = NULL; try {//combination cache key (instance name, method name, method parameter list) String CacheKey = Getcachekey (Joinpoint.gettarget (). GetClass (            ). GetName (), Joinpoint.getsignature (). GetName (), Joinpoint.getargs ());            Element element = Cache.get (CacheKey);            If the cache is in the cache, take if (element! = null) {result = Element.getobjectvalue (); } else {//execute method, get results result= Joinpoint.proceed ();            The result is cached Cache.put (new Element (CacheKey, (Serializable) result));        }} catch (Throwable e) {e.printstacktrace ();    } return result; }/** * Remove cache */public void RemoveCache (Joinpoint point) {//Get instance name String ClassName = Poi        Nt.gettarget (). GetClass (). GetName ();        list<?> list = Cache.getkeys ();            for (int i = 0; I<list.size (); i++) {String CacheKey = string.valueof (List.get (i));            Remove the cache if (Cachekey.startswith (ClassName)) {Cache.remove (CacheKey), beginning with this instance name; }}}/** * Combination cache Key */private string Getcachekey (String targetName, String methodName, Ob        ject[] arguments) {stringbuffer sb = new StringBuffer (); Instance Name + method name Sb.append (targetName). Append (".").          Append (MethodName);  if (arguments! = null) && (arguments.length! = 0)) {          Combination method parameters for (int i = 0; i < arguments.length; i++) {if (Arguments[i] instanceof                      String[]) {string[] Strarray = (string[]) arguments[i];                      Sb.append (".");                      for (String Str:strarray) {sb.append (str); }}else{Sb.append (".").                  Append (Arguments[i]);    }}} return Sb.tostring (); }}

Third, run the test

1, first comment before Testdao in the Ehcache comment, otherwise do not see the effect

@SuppressWarnings ("unchecked")/** @Cacheable (value= "Testdao", key= "' list") */public list<testinfo> getList ()      {String hql = "from TestInfo";     Query query = sessionfactory.getcurrentsession (). CreateQuery (HQL);    Query.setcacheable (TRUE); return Query.list ();} /** @Cacheable (value= "Testdao", key= "' View ' + #id") */public testinfo getInfo (String ID) {return (TestInfo) session Factory.getcurrentsession (). Get (Testinfo.class, id);} /** @Caching (put={@CachePut (value= "Testdao", key= "' View ' + #testInfo. Id")}, evict={@CacheEvict (value= "Testdao", key    = "' List '")}) */public testinfo update (TestInfo testinfo) {testinfo.setname ("789"); Update return testinfo;} /** @Caching (evict={@CacheEvict (value= "Testdao", key= "' View ' + #id"), @CacheEvict (value= "Testdao", key = "' List '")}) */public void Delete (String id) {//delete}/** @CacheEvict (value= "Testdao", allentries=true) */public void D Eleteall () {//deleteall}

2. Testing

Access the "Http://localhost:8080/demo1/hello/list2" address for the first time, enter the surround notification to increase the cache, and then execute the method to cache the results

The second visit, the cache has data, can be used directly, no need to execute the method

Click "Delete" button, will go to remove the cache of the post-notification, and then match the instance name, delete the list of the cache

Instance code address: Https://github.com/ctxsdhy/cnblogs-example

Using Ehcache in spring based on AOP

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.