如果我使用 cacheBuilder,如何为具体缓存自定义 expireAfterWrite?

How to customize expireAfterWrite for concrete cache if I use cacheBuilder?

基于 this answer 我尝试为“customCache”使用自定义 expireAfterWrite

所以我的配置是这样的:

@Configuration
@EnableCaching
public class CaffeineCacheConfig {

    ...

    @Bean
    public CaffeineCacheManager cacheManager(Caffeine<Object, Object> caffeineCacheBuilder) {
        CaffeineCacheManager result = new CaffeineCacheManager();
        result.setCaffeine(caffeineCacheBuilder);
        return result;
    }

    @Bean
    public Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .recordStats();
    }

    @Bean
    public CaffeineCache customCache() {
        return new CaffeineCache("customCache",
                Caffeine.newBuilder()
                        .maximumSize(10000)
                        .expireAfterWrite(60, TimeUnit.MINUTES)
                        .recordStats()
                        .build());
    }
}

然后在代码库中我使用:

“自定义缓存”

Cache cache = cacheManager.getCache("customCache")
String result = cache.get("myKey", () -> "cachedValue")

根据我的实验,它在缓存中将值保留 60 秒,我预计为 60 分钟。

如何达到预期的效果?

我认为更好的方法如下。

@Configuration
@EnableCaching
public class CaffeineCacheConfig
{
    @Bean
    public CacheManager cacheManager(
            @Qualifier("oneMinuteCache") final Cache<Object, Object> oneMinuteCache,
            @Qualifier("oneHourCache") final Cache<Object, Object> oneHourCache)
    {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(
                new CaffeineCache("oneMinuteCache", oneMinuteCache),
                new CaffeineCache("oneHourCache", oneHourCache)));
        return cacheManager;
    }

    @Bean
    public Cache<Object, Object> oneMinuteCache()
    {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .recordStats()
                .build();
    }

    @Bean
    public Cache<Object, Object> oneHourCache()
    {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.HOURS)
                .recordStats()
                .build();
    }
}