Object caching using Spring, Ehcache

Caching is quite important to boost the application performance. There are many cache libraries in Java world, both commercial and open source. You should choose the existing library instead creating your own library. I see some guys in my previous companies develop their own cache, and it is not good for their project. Instead of spending time on project business features, guy spent much time to create the perfect library and maintain it through the project life cycle. Another case is using the Map and its relative classes for caching, it makes the application could not scalable and it does not provide the flexible caching mechanism the cache should have. Of course, we need to create the cache library if there is no good one in the market, but it is not true. There are many good cache libraries in Java world, one of them is Ehcache (http://ehcache.sourceforge.net/). Ehcache is the excellent library provides to community with high quality, good documentation, simple use and wide adoption by other popular frameworks. It takes development team 5-10 minutes to set up the caching (of course, if you are fresher you must spend more time to understand the caching mechanism), so why you do not use such library instead of creating your own library?

In our application, we use Spring as IoC container, though set up the Ehcache manager is the easy task but we would like to use it with our Spring beans and exposed it as Osgi service. Spring modules is the good library help us easy in configuration. It provides the consistent abstraction caching to our application, hence we can use our cache facade with other caching libraries such as JBoss cache, JCS, OScache without chaging our application code. You could download the Spring Modules at https://springmodules.dev.java.net/.

Here are the following steps to configure Ehcache in Spring application

Configuring caching via ehcache.xml file

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="ehcache.xsd">
 <!--
 Configure it if you have overflowToDisk or diskPersistent enabled for any cache.
 java.io.tmpdir - Default temp file path
 -->
 <diskStore path="java.io.tmpdir" />
 <!--
    Mandatory Default Cache configuration. These settings will be applied to caches
    created programmtically using CacheManager.add(String cacheName).
    The defaultCache has an implicit name "default" which is a reserved cache name.
    -->
 <defaultCache maxElementsInMemory="10000" eternal="false"
  timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
  diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
  diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
  memoryStoreEvictionPolicy="LRU" />
 <!--
    Sample cache named sampleCache1
    This cache contains a maximum in memory of 10000 elements, and will expire
    an element if it is idle for more than 5 minutes and lives for more than
    10 minutes.
    If there are more than 10000 elements it will overflow to the
    disk cache, which in this configuration will go to wherever java.io.tmp is
    defined on your system. On a standard Linux system this will be /tmp"

 -->
 <cache name="engroupCache" maxElementsInMemory="10000"
  maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true"
  diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
  timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
</ehcache>

Declarating Ehcache in Spring context

<bean id="cacheManager"
 class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
 <property name="configLocation">
  <value>classpath:ehcache.xml</value>
 </property>
</bean>
</pre>
<pre lang="xml" xml:space="preserve" xml:lang="xml">
<bean id="cacheProviderFacade"
 class="org.springmodules.cache.provider.ehcache.EhCacheFacade">
 <property name="cacheManager" ref="cacheManager" />
</bean>

Programmatic use

Using ehcache is so simple, a unit test to make the test whether configuration is set up correctly and take the simple put/get could explain all.

@RunWith(EngroupClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/cache-context.xml" })
public class CacheTest {
    @Autowired
    protected CacheProviderFacade cacheProviderFacade;
    @Test
    public void testCacheConfiguration() {
        Assert.assertNotNull(cacheProviderFacade);
        EhCacheCachingModel model = new EhCacheCachingModel();
        model.setCacheName("engroupCache");
        cacheProviderFacade.putInCache("a", model, new Integer(1));
        Integer fromCache = (Integer) cacheProviderFacade.getFromCache("a",
                model);
        Assert.assertEquals(new Integer(1), fromCache);
    }
}

Besides of using ehcache to create the session like variable in our application, we would like to use ehcache to cache SQL statement in iBatis and integrate with Terracotta to complete our distributing caching solution in our future project. I will keep the post on further caching usage in future posts. Keep reading!

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • blinkbits
  • BlinkList
  • blogmarks
  • BlogMemes
  • BlogMemes Cn
  • BlogMemes Fr
  • BlogMemes Jp
  • BlogMemes Sp
  • Blogosphere News
  • Blogsvine
  • blogtercimlap
  • Book.mark.hu
  • Bumpzee
  • co.mments
  • connotea
  • De.lirio.us
  • Design Float
  • DotNetKicks
  • DZone
  • eKudos
  • email
  • Fark
  • Faves
  • feedmelinks
  • Fleck
  • Furl
  • GeenRedactie
  • Global Grind
  • Gwar
  • Haohao
  • HealthRanker
  • Hemidemi
  • Identi.ca
  • IndianPad
  • Internetmedia
  • kick.ie
  • Kirtsy
  • laaik.it
  • Leonaut
  • LinkaGoGo
  • LinkArena
  • LinkedIn
  • Linkter
  • Live
  • Ma.gnolia
  • Meneame
  • MisterWong
  • MisterWong.DE
  • muti
  • MyShare
  • MySpace
  • N4G
  • Netvibes
  • Netvouz
  • NewsVine
  • NuJIJ
  • Ping.fm
  • PlugIM
  • Pownce
  • ppnow
  • Print
  • Propeller
  • Ratimarks
  • Rec6
  • Reddit
  • SalesMarks
  • Scoopeo
  • scuttle
  • Segnalo
  • Shadows
  • Simpy
  • Slashdot
  • Smarking
  • Socialogs
  • SphereIt
  • Spurl
  • StumbleUpon
  • Symbaloo
  • Taggly
  • TailRank
  • Technorati
  • ThisNext
  • Tipd
  • Tumblr
  • TwitThis
  • Upnews
  • Webnews.de
  • Webride
  • Wikio
  • Wikio FR
  • Wikio IT
  • Wists
  • Wykop
  • Xerpi
  • Yahoo! Buzz
  • YahooMyWeb
  • Yigg

Related posts:

  1. Testing Spring beans against database with DbUnit This is another post of testing series we wrote so...
  2. How to invoke Spring beans in other osgi bundle Spring Dynamic Modules helps integrating Spring beans to Osgi platform...
  3. Integration of Jackrabbit OCM and Spring (updated version) In the previous post Jackrabbit OCM and Spring, I have...
  4. Implementing enterprise integration solutions with Spring Integration In our last project, we faced 2 challenges of how...
  5. Spring Dynamic Modules (for Osgi) – the good complement for Osgi Spring Framework - the de factor standard IoC container...

Leave a Reply