There are times when we need to cache a large amount of data which take a long time to aggregate in memory. Of course we could use the usual collections using a HashMap but there are functionalities such as auto-expiry, write-to-disk, replication across cluster, etc that’d call for a slightly more dedicated library or framework. One such is EhCache (included in the famed Terracotta product).
In my case, I didn’t need the write to disk functionality but I did need setup of specific cache instances with auto-expiry based on specific business logic. Unfortunately the EhCache library does not come readily as an OSGi bundle. There is an instruction here to do this but it still required a bit of massaging before I could get a minimum configured EhCache API to allow in-memory caching. The MANIFEST.MF I used to create the bundle was as follows:
Manifest-Version: 1.0 Export-Package: net.sf.ehcache;version="2.6.2", net.sf.ehcache.store,net.sf.ehcache.terracotta, net.sf.ehcache.bootstrap, net.sf.ehcache.config, net.sf.ehcache.event Bundle-Vendor: Terracotta Bundle-Classpath: .,ehcache-core-2.6.2.jar, ehcache-terracotta-2.6.2.jar,slf4j-api-1.6.1.jar, slf4j-jdk14-1.6.1.jar,xml-apis.jar,xercesImpl.jar Bundle-Version: 2.5.2 Bundle-Name: EHCache bundle Created-By: 1.6.0_15 ( Apple Inc.) Bundle-ManifestVersion: 2 Import-Package: org.osgi.framework;version="1.3.0" ,javax.naming,javax.transaction.xa Bundle-SymbolicName: net.sf.ehcache Bundle-RequiredExecutionEnvironment: J2SE-1.5
Once this bundle is created, you can deployed it. From another consumer bundle, you can create specific caches and wrap them with an OSGi service. The configuration API example as follows:
Cache cache = manager.getCache("sampleCache"); CacheConfiguration config = cache.getCacheConfiguration(); config.setTimeToIdleSeconds(60); config.setTimeToLiveSeconds(120); config.setmaxEntriesLocalHeap(10000); config.setmaxEntriesLocalDisk(1000000);
You can wrap the cache get() and put() methods as desired. More details on what you can do in terms of interacting with EhCache here.
– Sarwar Bhuiyan