I have 2 different webapps (package into different war files) which needs to share some data via a cache (ehcache). I want to test out this idea with you to see if it works.
My idea is to create a service that bootstraps/accesses the ehcache and package that inside a jar. Then package that jar into the two wars:
- WAR1: ehcache-service.jar
- WAR2: ehcache-service.jar
Would ehcache work in such a configuration ?
You need to create a separate jar(s) with all classes (and all their dependencies) which instances you plan to cache and then deploy this jar as well as ehcache.jar as a library (depending of what application server you use the procedure might be different), in case of Tomcat 6 that means just copy jars to lib folder.
What happen then is that ehcache and your domain classes will be loaded by the classloader shared by all web applications, so instances will be cached and accessible in memory.
The dependencies of your domain classes are important, so you should see whether this approach is feasible in your project. It might also affect the way you restart the web applications.
Furthermore you should be aware that cache and sharing are not necessary the same thing. Cache is an optimization. If you put object instance into cache it might be evicted immediately if, for instance, cache doesn’t have enough storage space or eviction policy configuration. So may be you have to review the way you plan to use ecache in general.