设置spring @cacheable缓存10秒

时间:2013-11-04 13:15:46

标签: java spring spring-cache

我正在使用Spring framework 3.2.4编写一个java项目。

我有很多需要缓存10秒的SQL查询。

我知道使用@cacheable注释我可以缓存函数结果。

我不明白的是如何只缓存10秒钟。我知道你可以为可缓存的注释添加条件,但是我很难弄清楚如何为这些条件添加时序。

非常感谢有关该问题的任何信息。

2 个答案:

答案 0 :(得分:2)

Spring不提供开箱即用的功能,但它支持adapters,您可以使用例如guava adapter,其中包括允许配置到期超时。

<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>

答案 1 :(得分:1)

您可以使用调度程序定期调用驱逐缓存的服务方法。

调度程序:

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();
        }
}

服务:

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() {
        }
}
相关问题