ehCache getting Started

First create a singleton class (CacheHelper) to return an instance of cache:


package cache;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

import com.istarindia.android.pojo.ComplexObject;

public class CacheHelper {
private CacheManager cacheManager;
private Cache<Integer, ComplexObject> squareNumberCache;

public CacheHelper() {
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();

squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Integer.class, ComplexObject.class, ResourcePoolsBuilder.heap(10)));
}

public Cache<Integer, ComplexObject> getSquareNumberCacheFromCacheManager() {
return cacheManager.getCache("squaredNumber", Integer.class, ComplexObject.class);
}

private static class SingletonHolder {
private static final CacheHelper INSTANCE = new CacheHelper();
}

public static CacheHelper getInstance() {
return SingletonHolder.INSTANCE;
}
}


Next, wherever you want to use this singleton instance of the cache :

private static final CacheHelper cache = CacheHelper.getInstance();



Then in the same class say you want to place a ComplexObject instance in the cache against the userID corresponding to the ComplexObject, you do something like:

.
.
.
.
.
ComplexObject complexObject = null;
if (cache.getSquareNumberCacheFromCacheManager().containsKey(istarUserId)) {
// complexObject =
// cache.getSquareNumberCacheFromCacheManager().get(istarUserId);
System.out.println("Skip getting from cache");
} else {

complexObject = appComplexObjectServices.getComplexObjectForUser(istarUserId);
try {
cache.getSquareNumberCacheFromCacheManager().put(istarUserId, complexObject);
} catch (Exception e) {
e.printStackTrace();
}
}
.
.
.
.



Of course you still have to consider a strategy for updating your cache. Thinking about time is one way but modern webpages have complex relational structure and when one of the related entity changes the object should get updated as well. This is why a caching library such as ehcache should be closely integrated with an ORM library such as hibernate. Another point to consider is where do you want your cache to be stored, major options are in memory (RAM) or on disk (ROM). With the advent of ultra-fast ROMs both of them are competitive and its always wise to keep the RAM light for unprecedented spikes. Perhaps a hybrid strategy can be considered.



Comments

Popular posts from this blog

Using cookies with HttpURLConnection

SPARQL

ffmpeg for Google Speech API