我已经实现了缓存,现在我想添加过期时间。
如何使用
@Cacheable
在 Spring Boot 中设置过期时间?
这是一个代码片段:
@Cacheable(value="forecast",unless="#result == null")
我这样使用生活黑客:
@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
public static final String GAMES = "GAMES";
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);
return cacheManager;
}
@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500)
public void reportCacheEvict() {
System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
}
请注意,此答案使用 ehcache,它是受支持的 Spring Boot 缓存管理器之一,并且可以说是最流行的缓存管理器之一。
首先您需要添加到
pom.xml
:
<!-- Spring Framework Caching Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
在
src/main/resources/ehcache.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="forecast"
maxElementsInMemory="1000"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
来自参考文档
直接通过您的缓存提供商。缓存抽象是……嗯,是一个抽象而不是缓存实现。您使用的解决方案可能支持其他解决方案不支持的各种数据策略和不同的拓扑(例如 JDK ConcurrentHashMap) - 在缓存抽象中公开这些策略和拓扑是没有用的,因为没有支持支持。此类功能应在配置时或通过其本机 API 直接通过后备缓存进行控制。
您不能使用 @cacheable 表示法指定过期时间,因为 @cacheable 不提供任何此类可配置选项。
然而,提供 Spring 缓存的不同缓存供应商都通过自己的配置提供了此功能。例如,NCache/TayzGrid允许您创建具有可配置过期时间的不同缓存区域。
如果您已经实现了自己的缓存,则需要定义一种在缓存提供程序中指定过期的方法,并且还需要在解决方案中合并过期逻辑。
我使用咖啡因缓存,此配置的有效期为 60 分钟:
spring.cache.cache-names=forecast
spring.cache.caffeine.spec=expireAfterWrite=60m
@Scheduled
注解来实现这种驱逐策略。可以使用固定速率甚至 cron 表达式进行调度。
@Autowired
CacheManager cacheManager;
public void evictAllCaches() {
cacheManager.getCacheNames().stream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
}
@Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() {
evictAllCaches();
}
如果您使用咖啡因,则可以在
application.properties
文件中添加以下行:
spring.cache.caffeine.spec=expireAfterAccess=300s
您可以使用 localdatetime 对象来解决它。例如
@Cacheable(value="forecast", key = "#date.toString()")
public void forecast(LocalDateTime date){
//
}
public void call(){
forecast(LocalDateTime.now().minusHours(4));
}
您可以使用 localdatetime 对象来解决它。例如cahce将在4小时后过期。
积极方面:它不需要预定作业。
负面方面:旧数据仍然被缓存