Spring+ehcache Combat--the way of performance optimization

Source: Internet
Author: User

In the System Integration platform project encountered a more troublesome problem. The reason is that the use of the test system depends on the basic system published by the webservice to obtain the basic data, WebService cross-network transmission itself more or less on the system performance will have a certain impact on the transmission of the amount of data is larger, so the impact on the systems is even greater, However, another cause of system performance degradation is the frequent opening of the shutdown database. In response to these two problems, we took two solutions to minimize the performance impact. The first is that the webservice from the original transfer serialized object to the transfer JSON string, the second is the opening and closing of the database connection to cache processing. In this paper, we mainly discuss the second solution of Ehcache.

Ehcache is a very good caching framework, the configuration comes simple and powerful, in the project to cache the place there are two main, the first is to cache the entity object. This cache is added to the entity layer, primarily using Hibernate's Level two cache (always open the query cache at the same time) using spring's AOP annotations can be easily done, and in other query methods, the main use is Ehcache, used to cache the various objects returned by the method. It is easier to open Hibernate's query cache and level two cache. Do not introduce too much here, we mainly look at the use of Ehcache method.

1. First we use Interceptor, which defines two interceptors methodcacheinterceptor and Methodcacheafteradvice, which are used primarily to intercept methods that start with Get and find (for caching results). The second interceptor is primarily used to intercept the method at the beginning of the update to clear the cache. Let's take a look at the detailed code below:

public class Methodcacheinterceptor implements Methodinterceptor,initializingbean {private static final Log logger = Logf Actory.getlog (Methodcacheinterceptor.class);p rivate cache cache;public void Setcache (cache cache) {This.cache = cache;} Public Methodcacheinterceptor () {super ();} /** * Intercepts the Service/dao method and finds out if the result exists, assuming that it returns the value in the cache, 31 * * Otherwise, the database query results are returned. and put the query results in cache */public Object invoke (Methodinvocation invocation) throws Throwable {String targetName = Invocation.get This (). 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); Element element = Cache.get (CacheKey), if (element = = null) {Logger.debug ("hold up method, get method result and create CA Che........! "); result = Invocation.proceed (); element = new Element (CacheKey, (Serializable) result); SYSTEM.OUT.PRINTLN ("-----is not found in the cache. FindCache "); Cache.put (element);} Else{system.out.println ("find----in----cache");} return Element.getvalue ();} /** * Method of obtaining the cache key, the cache key is the unique identifier of an element in the cache * Cache key * Contains the package name + class name + method name, such as Com.co.cache.service.UserServiceImp L.getalluser */private string Getcachekey (String targetName, string methodname,object[] arguments) {StringBuffer SB = n EW 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 ();} /** * Implement Initializingbean. Check if the cache is empty */public void Afterpropertiesset () throws Exception {assert.notnull (cache, "need a cache. Please use Setcache (Cache) to create it. ");}
the code for the second interceptor is as follows:

public class Methodcacheafteradvice implements Afterreturningadvice,initializingbean {private static final Log logger = L Ogfactory.getlog (Methodcacheafteradvice.class);p rivate cache cache;public void Setcache (cache cache) {This.cache = Cache;} Public Methodcacheafteradvice () {super ();} 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 (ca Chekey.startswith (ClassName)) {cache.remove (CacheKey); SYSTEM.OUT.PRINTLN ("------Clear cache----"), Logger.debug ("Remove cache" + CacheKey);}} public void Afterpropertiesset () throws Exception {assert.notnull (cache, "need a cache. Please use Setcache (Cache) to create it. ");}
with these two interceptors, the next thing we need to do is to bring the two interceptors into the project to make it work, these configurations are all in the Ehcache.xml file, and the following is the detailed configuration of the file:

<?xml version= "1.0" encoding= "UTF-8"?

> <! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" ><beans ><!--Reference Ehcache configuration--><bean id= "Defaultcachemanager" class= " Org.springframework.cache.ehcache.EhCacheManagerFactoryBean "><property name=" Configlocation "><value >ehcache.xml</value></property></bean><!--define the Ehcache factory and set the cache name--><bean used Id= "EhCache" class= "Org.springframework.cache.ehcache.EhCacheFactoryBean" ><property name= "CacheManager" ><ref local= "Defaultcachemanager"/></property><property name= "CacheName" ><value> default_cache</value></property></bean><!--find/create CACHE blocker--><bean id= " Methodcacheinterceptor "class=" Com.co.cache.ehcache.MethodCacheInterceptor "><property name=" cache ">< Ref local= "EhCache"/></property></bean><!--flush cache blocker--><bean id= " Methodcacheafteradvice "class=" Com.co.cache.ehcache. Methodcacheafteradvice "><property name=" cache "><ref local=" EhCache "/></property></bean ><bean id= "Methodcachepointcut" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor" > <property name= "Advice" ><ref local= "Methodcacheinterceptor"/></property><property name= " Patterns "><list><value>.*find.*</value><value>.*get.*</value></list> </property></bean><bean id= "Methodcachepointcutadvice" class= " Org.springframework.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></beans>


in this way, the configuration of the interceptor and the cache configuration introduced in the project, the cache configuration information is mainly in the Ehcache.xml file, specific information such as the following:

<ehcache><diskstore path= "H:\\temp\\cache"/><defaultcache maxelementsinmemory= "eternal=" False "timetoidleseconds=" timetoliveseconds= "overflowtodisk=" true "/><cache name=" Default_cache " Maxelementsinmemory= "10000" eternal= "false" timetoidleseconds= "300000" timetoliveseconds= "600000" overflowToDisk= " True "/></ehcache>  

at this point our corresponding configuration has been done, let us set up a test class to test whether the cache is working, here we mainly use the class has three, to see the detailed code:

Public interface Testservice {public List getallobject ();p ublic void Updateobject (Object object);}
Testservice is the calling interface, and the following testserviceimpl is actually present, code such as the following:

public class Testserviceimpl implements Testservice {public List getallobject () {SYSTEM.OUT.PRINTLN ("--- The element does not exist within the testservice:cache. Find and put in the cache. "); return null;} public void Updateobject (Object object) {System.out.println ("---testservice: Updates the object, the cache created by this class will be remove! ");}}
The following junittestclass are the real test class. The code is as follows:

public class Junittestclass {@Testpublic void TestRun () {String default_context_file = "/ Applicationcontext.xml "; ApplicationContext context = new Classpathxmlapplicationcontext (default_context_file); Testservice Testservice = (testservice) context.getbean ("Testservice");//Find Testservice.getallobject () for the first time;// The second time to find Testservice.getallobject ();//Run the Update method (should clear the cache) Testservice.updateobject (null);// Third time find Testservice.getallobject ();}} 

Analysis of the test code, when the first run Getallobject () method, because it is the first time to run the query operation, will be methodcacheinterceptor intercept. When Methodcacheinterceptor discovers that there is no hit cache, run the Invoke () method. Let the program go to the database query (this program only simulates the database query, and does not really query the database.) Just what it means is not different from querying the database), we see that this is going to run Testserviceimpl's Getallobject () method, print out a statement at the same time in the print interceptor "-----non-cache lookup. Put cache "statement after lookup. The Testserviceimpl Getallobject () method is no longer run when the method is run for the second time because the cache already exists. At the same time, only the "find----in----cache" statement in the interceptor will be intercepted by Methodcacheafteradvice when the Updateobject () method is run. and runs Testserviceimpl's Updateobject () method, it prints "---testservice: Updated object. The cache generated by this class will be removed and the "------Delete cache----" statement in the interceptor when the third lookup is run. Because the cache has been cleared, this output will be the same as the first statement, and the following to verify that our guess is correct:


The output is the same as we have predicted, which means that the Ehcache cache has already worked in the program.

Spring+ehcache Combat--the way of performance optimization

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.