0

我的配置:

@Bean
public CaffeineCacheManager cacheManager() {
    return new CaffeineCacheManager();
}

@Bean
public CaffeineCache testCache() {
    return new CaffeineCache("test_cache",
            Caffeine.newBuilder()
                    .maximumSize(10000)
                    .expireAfterAccess(30, TimeUnit.SECONDS)
                    .expireAfterWrite(30, TimeUnit.SECONDS)
                    .recordStats()
                    .build());
}

测试代码:(连续读取缓存 3 次,读取间隔 45 秒)

static int value = 1;
    ...

    Cache testCache = cacheManager.getCache("test_cache");
    System.out.println("read " + testCache.get("myKey", () -> value++));
    try {
        Thread.sleep(45000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("read " + testCache.get("myKey", () -> value++));
    try {
        Thread.sleep(45000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("read " + testCache.get("myKey", () -> value++));

实际结果:

read 1
read 1
read 1

预期结果:缓存在 30 秒后被驱逐:

read 1
read 2
read 3

我错了什么?

怎么修 ?

4

1 回答 1

2

仅供参考,CaffeineCacheManager并且CaffeineCache是真正的 Caffeine 缓存周围的 Spring 包装器。

org.springframework.cache.caffeine. CaffeineCache实现org.springframework.cacheCache(强调两者的包装)

至于你的问题,CaffeineCacheManager从你返回的实际上@Bean没有缓存。所以当你调用 时cacheManager.getCache("test_cache"),你会得到一个由 Spring 动态创建的缓存,称为动态缓存。而这个缓存的expireAfterAccessexpireAfterWrite没有设置。因此,1您放入其中的内容永远不会被驱逐。

要获得预期的行为,您需要添加CaffeineCache到缓存管理器。检查我的答案

于 2021-07-27T14:54:19.797 回答