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.

 DevX Skillbuilding from IBM developerWorks
 RIA Run Contest: Build Next-Gen Apps in Microsoft Silverlight 2
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
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%.

RIM Ups Ante With Mobile Software Push
Novell Readies Silverlight Clone for Linux
Yahoo Pitches The 'Next Generation of Search'
Alfresco's Latest ECM: Prying Open a Sector?
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads for the JON 2.0
Out with the Old, in with the New at JavaOne
Trolltech Expands WebKit Footprint

Create Secure Java Applications Productively, Part 1: Use Rational Application Developer and Data Studio
.NET Building Blocks: Custom User Control Fundamentals
Secure Internet File-Sharing with PHP, MySQL, and JavaScript
Getting Started with TBB on Windows
Moving to VoIP: Should You Go It Alone?
Introduction to the WPF Command Framework
7.0, Microsoft's Lucky Version?
Will Hyper-V Make VMware This Decade's Netscape?
Eliminate Fragmentation Frustration with Netbiscuits
Taming Trees: Building Branching Structures

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



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES