Pregunta

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.

¿Fue útil?

Solución 2

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>

Otros consejos

You can use a Scheduler to periodically call a service method which evicts the caches.

Scheduler:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.beans.factory.annotation.Autowired;

public class Scheduler {

        @Autowired
        private SomeService someService;

        @Scheduled(fixedRate = 10000)
        public void evictCaches() {
                someService.evictCaches();
        }
}

Service:

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SomeService {

        @CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
        public void evictAllCaches() {
        }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top