如果使用cachebuilder,如何为具体缓存定制expireafterwrite?

olmpazwi  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(419)

基于这个答案,我尝试使用定制的 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分钟。
如何达到预期的效果?

ss2ws0br

ss2ws0br1#

我认为更好的方法是如下。

@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();
    }
}

相关问题