CaffeineCacheManager() 构造函数需要 cacheName 吗?

Is cacheName needed at CaffeineCacheManager() constructor?

我有一个 MultipleCacheManager class 看起来像这样:

@EnableCaching
public class MultipleCacheManagerConfig {

    @Bean
    @Primary
    public CacheManager mainCacheManager() {
        // instantiate caffeine manager and add in specifications
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("example1", "example2");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(4, TimeUnit.HOURS)
                .recordStats());
        return cacheManager;
    }

    // these are examples of alternate cache managers if another cache needs to be configured differently.

    public CacheManager alternateCaffeineManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("example3");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.HOURS)
                .recordStats());
        return cacheManager;
    }

我是否需要在 CaffeieneCacheManager() 构造函数中实际传递我的缓存名称?只要 @Cacheable 有 属性 @Cacheable(cacheName = "example1", cacheManager = "mainCacheManager") 有关系吗?缓存管理器在技术上已经连接到此时的名称。

您总是可以首先在 documentation

中找到有用的信息

public void setCacheNames(@Nullable Collection cacheNames) Specify the set of cache names for this CacheManager's 'static' mode. The number of caches and their names will be fixed after a call to this method, with no creation of further cache regions at runtime.

还有

CaffeineCacheManager(String... cacheNames) Construct a static CaffeineCacheManager, managing caches for the specified cache names only.

因此,如您所见,在构造函数上提供缓存名称意味着此缓存管理器将来只能处理那些缓存名称。所以你不能指示 cacheManager 在将来动态处理其他 cacheNames。

您仍然需要通过注释传递 ​​cacheNames @Cacheable(cacheName = "example1", cacheManager = "mainCacheManager") 就好像您有多个使用此 cacheManager 的方法一样,这两个方法每个都有自己的 cacheName 是有意义的。

@Cacheable(cacheName = "example1", cacheManager = "mainCacheManager")
public String method1( String a) {
   ....
}


@Cacheable(cacheName = "example2", cacheManager = "mainCacheManager")
    public String method2( String b) {
       ....
}

这 2 个不同的 cacheName 通知 cacheManager 它应该处理 2 个不同的缓存命名空间,并且注释通知 cacheManager 哪个 cacheName 与此方法相关。