2013-11-04 68 views
1

我在寫一個使用Spring框架3.2.4的java項目。設置spring @cacheable緩存10秒

我有很多SQL查詢需要緩存10秒。

我知道用@cacheable註釋我可以緩存函數結果。

我不明白的是如何緩存只有10秒。我知道你可以爲可緩存註釋添加條件,但是我很難找出如何爲這些條件添加時間。

有關該問題的任何信息將不勝感激。

回答

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