Friday, May 1, 2009

Setting up EhCache using Spring

Setting up EhCache using Spring

Ehcache is a pure Java cache with the following features: fast, simple, small foot print, minimal dependencies, provides memory and disk stores for scalability into gigabytes, scalable to hundreds of caches are a pluggable cache for Hibernate.

Here I am going to explain how to integrate ehcache with spring.

Following jar files are required in the class path in order to run this application J
ehcache-1.6.0-beta3.jar
spring-2.5.5.jar

We use ehcache.xml to configure all cache related information.


<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="javatchEhcache"
maxElementsInMemory="1000"
eternal="true"
overflowToDisk="false"/>
<defaultCache
maxElementsInMemory="200"
maxElementsOnDisk="500"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"/>
</ehcache>

Back to spring configuration, we have to configure ehcache dependencies in to spring.

beans.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ecManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>

<bean id="mycache" class=" com.javatch.ehcache.example.EhCacheManager" init-method="setupCache">
<property name="cacheManager" ref="ecManager"/>
</bean>

</beans>

Create ehcache reference from java
EhCacheManager.java
package com.javatch.ehcache.example;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class EhCacheManager {

private CacheManager cacheManager;
private static Cache myCache = null;

public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}

private void setupCache() {
String cacheName = "javatchEhcache";
System.out.println("cache Name [" + cacheName + "]");
myCache = cacheManager.getCache(cacheName);
}

private static Element getValues(String key){
Element value = myCache.get(key);
if(value!=null) {
System.out.println("from cache");
return value;
} else {
// DAO call goes here...
myCache.put(new Element(key, "Object"));
System.out.println("not from cache");
}
return value;
}
private static void setValuesIntoCache(){
myCache.put(new Element("OS", "OSCache"));
myCache.put(new Element("OD", "OracleDBCache"));
}
public static void main(String[] args) {

BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
System.out.println(factory.getBean("mycache"));
setValuesIntoCache();
getValues("NB");

}

}

Thank you 

No comments: