我在写一个使用Spring框架3.2.4的java项目。设置spring @cacheable缓存10秒
我有很多SQL查询需要缓存10秒。
我知道用@cacheable
注释我可以缓存函数结果。
我不明白的是如何缓存只有10秒。我知道你可以为可缓存注释添加条件,但是我很难找出如何为这些条件添加时间。
有关该问题的任何信息将不胜感激。
我在写一个使用Spring框架3.2.4的java项目。设置spring @cacheable缓存10秒
我有很多SQL查询需要缓存10秒。
我知道用@cacheable
注释我可以缓存函数结果。
我不明白的是如何缓存只有10秒。我知道你可以为可缓存注释添加条件,但是我很难找出如何为这些条件添加时间。
有关该问题的任何信息将不胜感激。
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>
您可以使用调度程序定期调用驱逐高速缓存的服务方法。
调度:
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() {
}
}