Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where exactly should I put ehcache.xml in my project?

Tags:

java

ehcache

I've recently began using EHCache for caching purposes. I know, how to use it in Java code, but I'm still not sure about the configuration file.

So, I have an ear project, that includes several war modules. If all these modules use ehcache, should I put a copy of ehcache.xml in WEB-INF for each module, or put it somewhere in ear file itself (META-INF maybe?)

Also, it's not clear from the documentation, whether or not all these modules will use the same cache instance? The application is deployed at glassfish, will EHCache run the same cache for each module in ear, or each module will get his own singleton instance when used like this:

CacheManager singleton = CacheManager.create();
like image 713
SPIRiT_1984 Avatar asked Aug 26 '15 05:08

SPIRiT_1984


1 Answers

  1. According to ehcache.xml file. There is no rule where you will put this file, but if you are working on a big project I presume that you have several profiles (e.g. for QA, DEV, PROD). As ehcache may differ depending on profile (for example, if you have ehcache jms replication enabled) you can have different JMS Server IPs set up there or amount of objects in cache regions may differ, so I suggest to put in where you have profile-dependent file (e.g. web.xml, log4j.properties). Then if you have context configuration in a separate xml file like:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context-config.xml</param-value>
</context-param>

then you may add in that context-config.xml file:

<import resource="context-config.xml"/>

That context-config.xml file may contain description of cacheManager bean, that you will be able to Autowire where do you need it. So the context-config.xml may look like:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

        <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
            <property name="configLocation" value="classpath:ehcache.xml"/>
        </bean>

    </beans>

Answering your second question. From my example, it will depend on how you will define this bean, you can define it as a singleton and then you will have only one instance of cacheManager or you can leave the instantiation to Spring. In my opinion, you can autowire cacheManager to the class with general logic for cache invalidation or cache "creation" and that will make a lot of sense. Hope that I helped you.

like image 81
edward_wong Avatar answered Oct 10 '22 23:10

edward_wong