javaspringspring-cache

settings spring @cacheable to cache for 10 seconds


I'm writing a java project using Spring framework 3.2.4.

I have many SQL queries that needs to be cached for 10 seconds.

I know that with @cacheable annotation i can cache functions result.

What I don't understand is how to cache for only 10 seconds. i know you can add conditions to the cacheable annotation but it's hard for me to figure out how to add timing to these conditions.

any information regarding the issue would be greatly appreciated.


Solution

  • Spring doesn't offer this out of the box but it supports adapters and you may use for example guava adapter which among other things allows configure expiration timeout.

    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
      <property name="caches">
        <list>
          <bean name="testCache"
                class="org.hypoport.springGuavaCacheAdapter.SpringGuavaCacheAdapter">
            <property name="expireAfterAccessInSeconds" value="10"/>
            <property name="expireAfterWriteInSeconds" value="10"/>
          </bean>
        </list>
      </property>
    </bean>