advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Add Object Caching Using Spring, AOP, and Ehcache :

 

The Solution

Implement a method return data caching interceptor using Ehcache to cache the object graph for subsequent calls to the getAllAtms method. Ehcache is configurable through an XML file—no surprise there, eh?

To begin, create a new file, atmlocator-ehcache.xml, with the following contents:

<ehcache>
 <diskStore path="java.io.tmpdir" />
 <defaultCache maxElementsInMemory="10" eternal="false"
	timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
  <cache name="getAllAtms" maxElementsInMemory="50" eternal="false"
      overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="86400" />
</ehcache>
The configuration file starts out with a diskStore and a path attribute. The platform-independent java.io.tmpdir will be where you store object cache overflow. Adding a defaultCache configuration (as shown above) is a safeguard in case you need to cache other objects in the future but do not want to specify a new cache entry.

The next element is specific for the ATM locator service. The name is the same name as the method that will be cached (remember that—it will become more important when you implement the cache interceptor).

While tuning Ehcache configurations, it's useful to adjust the maxElementsInMemory routinely—this is the point at which any other storage medium will be used once the threshold has been exceeded.

Ehcache uses the next attribute "eternal" to determine whether or not an object ever expires. If eternal is set to true, an object will never expire. In this case, you want your objects to expire after a period of time. OverflowToDisk is self explanatory—if set to true, and the memory store has reached the maximum number of objects in memory, objects will be written to disk at the location you specify for diskStore path. TimeToIdleSeconds is used to determine when an object is set expire after a period of time in which it is not used or idle. You don't care how long your objects are idle before they expire, you care about the overall time to live. The timeToLiveSeconds attribute expires an object after the set period of time—no matter how active or inactive the cache has become. This service's requirements state that the cache should expire after 24 hours or 86400 seconds every day.

You're not quite done with your Ehcache configuration yet. In order to use Ehcache in this application, you need to create a single instance of the CacheManager class. Add the following Spring bean within the atmlocator-core-beans.xml file:

<bean id="appCacheManager" class="net.sf.ehcache.CacheManager">
 <constructor-arg index="0" type="java.net.URL"
	value="classpath:jbriscoe/article/spring/caching/atmlocator-ehcache.xml" />
</bean>
For the final comnfiguration step, Spring calls a CacheManager constructor and passes in the atmlocator-ehcache.xml configuration file that you just created.

The next step is to implement the method return data-caching interceptor. There are several things you're trying to achieve in this step:

  • Intercepting should be non-destructive to the application. In other words, the application should not know that caching is even going on at all.
  • The applied caching interceptor should be able to handle any method call. Methods with any number of arguments and methods that don't return data should not break the interceptor. However, if you are intercepting methods with no return data, you should re-evaluate your pointcut expression—it certainly helps boost performance when Spring doesn't have to look at methods unnecessarily.
  • Method calls with an argument that is static in nature but has routine argument values should be cacheable. For example; suppose you have a Ehcache cache configuration with a name like getAtm(1). When the interceptor is applied to this method getAtm, the interceptor can look at the value of the arguments being passed to the cache and make a match, thus performing a cache. This is useful in instances where a method returns different data based on the argument passed to it, but you have a static value you that you pass routinely to the method and you want that data cached because it is unchanging. Without this mechanism, the cache for getAtm(2) returns the cache for getAtm(1) and this returns incorrect data. The solution to this problem is to add logic within the interceptor to handle this type of exception.

The implementation of the MethodCachingInterceptor can be seen in Listing 5 but don't worry, we'll go through it line-by-line.

Start with the CacheManager. The Spring framework injects the CacheManager into the MethodCachingInterceptor. This is used to perform the actual caching of data. Attempt to load the cache based on the method name. If it is null, there is no cache configuration for the method and no arguments specified. Now attempt to load the cache again—this time with an argument list. If you're able to retrieve the cache, then set it as the method's return value. Otherwise, create a new cache entry after method execution.

Before you try out the interceptor, you need to tell Spring about it. Add a new methodCachingInterceptor instance to the atmlocator-core-beans.xml file:

<<bean id="methodCachingAdvice"
	class="jbriscoe.article.spring.caching.interceptor.MethodCachingInterceptor">
  <property name="cacheManager" ref="appCacheManager" />
</bean>
One last thing: Add a new AOP advisor to hook up the interceptor you created by adding the following bean to your aop:config:
<aop:advisor id="methodCachingAdvisor"
	advice-ref="methodCachingAdvice" pointcut-ref="getAllAtmsPointcut" />
Now, run the final unit test to see your work in action. You should see output similar to the following code:
INFO  AbstractSingleSpringContextTests - Loading context for:
classpath:jbriscoe/article/spring/caching/atmlocator-core-beans.
xml,classpath:jbriscoe/article/spring/caching/atmlocator-atms-beans.xml
INFO  MethodCachingInterceptor - Attempting cacheManager.getCache first run
(no args lookup).
INFO  MethodCachingInterceptor - Cache Config. Found: getAllAtms
INFO  StaticAtmDaoImpl - Actually performing all atms lookup.
INFO  MethodCachingInterceptor - Created new CacheElement entry and stored in cache.
INFO  MethodTimingInterceptor - Method Invocation
[jbriscoe.article.spring.caching.dao.impl.StaticAtmDaoImpl.getAllAtms] Total Time:
10(seconds) 10015(millis)
INFO  MethodCachingInterceptor - Attempting cacheManager.getCache first run
(no args lookup).
INFO  MethodCachingInterceptor - Cache Config. Found: getAllAtms
INFO  MethodCachingInterceptor - Cache Element Found
INFO  MethodCachingInterceptor - Using Cached Element for methodReturn.
INFO  MethodTimingInterceptor - Method Invocation
[jbriscoe.article.spring.caching.dao.impl.StaticAtmDaoImpl.getAllAtms] Total Time:
0(seconds) 0(millis)

Service Facelift!

Just looking at the test results, you can see that the first method invocation of getAllAtms took 10 seconds and the second invocation took 0 seconds! Quite an improvement! This opens the door for you to increase a positive user experience by being much more prompt when a request comes along.

Related Resources

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs