首页 文章

设置spring @cacheable缓存10秒

提问于
浏览
1

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

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

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

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

任何有关该问题的信息将不胜感激 .

2 回答

  • 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

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

    调度:

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

相关问题