Geo Thomas
Geo Thomas

Reputation: 1159

Spring MVC - configuring Ehcache - Not caching

I am trying to integrate Ehcache with my Java Spring MVC Web Applications. I have followed the instructions from the following article: https://dzone.com/articles/implementing-ehcache-using. I have added the following dependency to my pom.xml file:

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.9.0</version>
</dependency>

My ehcache.xml is as follows:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="true"
    monitoring="autodetect"
    dynamicConfig="true">

    <diskStore path="java.io.tmpdir" />

    <cache name="swcmRestData"
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000"
        eternal="false"
        diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="300" timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>

</ehcache>

I have the following entries in my root-context.xml:

<!-- EhCache Configuration  -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml" p:shared="true"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/>

And I have a method for which I want to enable ehCache:

@Cacheable(value="swcmRestData", key="url")
public <T> T getEntity(String url, java.lang.Class<T> gt) throws RestException
{
    T t = restClientService.getEntity(url, gt);
    return t;
}

I want the data to be retrieved from the ehCache if the same url is passed to the specified method. I do not get any errors while running the code. But looks like the caching is not working. Is there anything that I am missing here

Upvotes: 1

Views: 1371

Answers (1)

Louis Jacomet
Louis Jacomet

Reputation: 14510

Two things that could be the cause of the problem:

  1. You are missing the Spring configuration so that there is a link between the defined beans and the caching annotation. Effectively that's point 2 in the article you link which you do not mention here.
  2. As suggested in comments, the method you are caching is called from within the same class. That's a limitation of Spring AOP implementation when using proxies. If you configure Spring to do bytecode weaving it will work.

If none of the above are the source of error, please provide more information on your setup.

Upvotes: 1

Related Questions