In-Memory caching using EhCache in OSGi

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.terracotta,
Bundle-Vendor: Terracotta
Bundle-Classpath: .,ehcache-core-2.6.2.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"
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();

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

In-Memory caching using EhCache in OSGi

One thought on “In-Memory caching using EhCache in OSGi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s