Thursday, March 13, 2008

EhCache 1.4 implementation

Here, I am putting EhCache implementation with simple JAVA application.

JAR need to add on class path or LIB.

ehcache-1.4.0.jar
backport-util-concurrent-3.0.jar
commons-logging-1.0.4.jar

(These all are available on ehCache binary download .)

Method 1:- Simplest one
Create simple JAVA program that will get default cache configuration from JAR files.
Here is most simplest code.


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

public class Main{
public static void main(String args[]){
try{
cacheManager = new CacheManager();
//Create cache with some default parameters.
cache = new Cache("testCache", 1, true, false, 5, 2);
cacheManager.addCache(cache);

cache.put(new Element("key", "value"));
//Write you code, and then get your cached value again as follow.
System.out.println(cache.get("key").getValue());
//Its good practice to close cacheManages before end of program, or in GC method.
cacheManager.shutdown(); //

}catch(CacheException cacheEx){
cacheEx.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}

}



Method 2:- Using pre-configured XML file.

We can also made our own configuration while implementing ehCache, Its configured in XML file.

simpler form of ehCache file as under all value as in default form.






class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic,
multicastGroupAddress=230.0.0.1,
multicastGroupPort=4446, timeToLive=32"
propertySeparator=","
/>
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskSpoolBufferSizeMB="30"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>




JAVA code that use above file,


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

public class Main{
public static void main(String args[]){
try{
//**Only change on this line.**
cacheManager = CacheManager.create(Main.class.getResource("ehcache1.xml"));
//Create cache with some default parameters.
cache = new Cache("testCache", 1, true, false, 5, 2);
cacheManager.addCache(cache);

cache.put(new Element("key", "value"));
//Write you code, and then get your cached value again as follow.
System.out.println(cache.get("key").getValue());
//Its good practice to close cacheManages before end of program, or in GC method.
cacheManager.shutdown(); //

}catch(CacheException cacheEx){
cacheEx.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}

}



These are the initial method to start with ehCache.