If you need to cache objects in your system, Ehcache is a simple cache written in Java, widely used and well tested. I will present here a short tutorial on how to use EhCache for people who don't want to look around the documentation at first, but just want to test if it works in their project and to see how easy it is to setup.
Installation
Download Ehcache from the Download link on http://ehcache.sourceforge.net. Current release is 1.2.
Unpack Ehcache with an unpacker that knows the tgz format. For unix users, it is trivial, for windows users, 7zip is a free (and open-source) unpacker. It is probably the most popular, but there are other ones like tugzip or izarc or winrar.
In your java project you need to have ehcache-1.2.jar, commons-collections-2.1.1.jar and commons-logging-1.0.4.jar (versions numbers may vary) in your classpath, those libraries are shipped with ehcache.
Cache Configuration
Write an ehcache.xml file where you describe what cache you want to use. There can be several files per project, several cache descriptions per file. I use here a persistent cache. Configuration file is well described at http://ehcache.sourceforge.net/documentation/configuration.html
<ehcache>
<cache name="firstcache" maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0" diskPersistent="true" diskExpiryThreadIntervalSeconds="120"/>
</ehcache>
Code
static {
//Create a CacheManager using a specific config file
cacheManager = CacheManager.create(TestClass.class.getResource( "/config/ehcache.xml"));
cache = cacheManager.getCache("firstcache");
}
/**
* retrieves value from cache if exists
* if not create it and add it to cache */
public String doit(String key, String value) {
//get an element from cache by key
Element e = cache.get(key);
if (e != null) {
value = (String)e.getValue();
LOGGER.info("retrieved "+ value+" from cache ");
}
else {
value = "new value" ;
cache.put(new Element(key, value));
}
return value;
}
/**
* refresh value for given key */
public void refresh(String key) { cache.remove(key); }
/**
* to call eventually when your application is exiting */
public void shutdown() { cacheManager.shutdown(); }
Conclusion
Using EhCache is as simple a using a Java Map with an additional configuration file.
hi there,
ReplyDeletethe line with "static { //Create a CacheManager"
is a VERY VERY WIDE LINE in firefox 1.5.0.3 on windows xp.
Not exactly short on IE7 :)
ReplyDeleteSame for Firefox 3.5 :)
ReplyDeleteNo need for cache.initialise() ?
ReplyDeletefix "as easy a java"
ReplyDeleteas easy as java
refresh is not the best method name for remove functionality
ReplyDelete