到期时间@cacheable spring boot

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)

  • 很好,但这将驱逐所有条目,无论是旧的还是新的。 (11认同)

Ste*_*oll 10

参考文档

直接通过缓存提供程序.缓存抽象是......好吧,抽象不是缓存实现.您正在使用的解决方案可能支持各种数据策略和其他解决方案所不具备的不同拓扑(例如JDK ConcurrentHashMap) - 暴露在缓存抽象中仅仅因为没有后备支持而无用.在配置或通过其本机API时,应通过后备缓存直接控制此类功能.

  • 抱歉,您的示例没有链接。听起来与我完全无关。该属性用于配置Web资源的缓存时间。 (2认同)

Ste*_*eve 7

请注意,这个答案使用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)

  • 哦,是的,有!:)这是EHCache配置的默认位置.其他缓存库可能会期望不同的位置. (7认同)

sla*_*dan 6

我使用咖啡因缓存,此配置的有效期为 60 分钟:

spring.cache.cache-names=forecast
spring.cache.caffeine.spec=expireAfterWrite=60m
Run Code Online (Sandbox Code Playgroud)


小智 5

您不能使用 @cacheable 表示法指定到期时间,因为 @cacheable 不提供任何此类可配置选项。

然而,提供弹簧缓存的不同缓存供应商已经通过他们自己的配置提供了这个功能。例如,NCache / TayzGrid允许您创建具有可配置到期时间的不同缓存区域

如果您实现了自己的缓存,则需要定义一种在缓存提供程序中指定到期时间的方法,并且还需要将到期逻辑合并到您的解决方案中。