nol*_*ole 30 java caching spring-cache
我已经实现了缓存,现在我想添加一个到期时间.
如何在春季启动时设置到期时间@Cacheable
?
这是一段代码:
@Cacheable(value="forecast",unless="#result == null")
Run Code Online (Sandbox Code Playgroud)
Atu*_*tum 23
我使用像这样的生活黑客
@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()));
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这个答案使用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>
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
我使用咖啡因缓存,此配置的有效期为 60 分钟:
spring.cache.cache-names=forecast
spring.cache.caffeine.spec=expireAfterWrite=60m
Run Code Online (Sandbox Code Playgroud)
小智 5
您不能使用 @cacheable 表示法指定到期时间,因为 @cacheable 不提供任何此类可配置选项。
然而,提供弹簧缓存的不同缓存供应商已经通过他们自己的配置提供了这个功能。例如,NCache / TayzGrid允许您创建具有可配置到期时间的不同缓存区域。
如果您实现了自己的缓存,则需要定义一种在缓存提供程序中指定到期时间的方法,并且还需要将到期逻辑合并到您的解决方案中。
归档时间: |
|
查看次数: |
36029 次 |
最近记录: |