javaspringspring-bootcachingcaffeine-cache

Is cacheName needed at CaffeineCacheManager() constructor?


I have a MultipleCacheManager class that looks like this:

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

Do I need to actually pass in my cacheNames in the CaffeieneCacheManager() constructor? As long as @Cacheable has the property @Cacheable(cacheName = "example1", cacheManager = "mainCacheManager") does it matter? The cache manager is technically already connected to the name at that point.


Solution

  • You can always find usefull information first in the 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.

    Also

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

    So as you see, providing the cacheNames on the constructor means that this cacheManager will be able to handle only those cacheNames in the future. So you could not instruct that cacheManager to handle other cacheNames dynamically in the future.

    You still need to pass the cacheNames through the annotation though @Cacheable(cacheName = "example1", cacheManager = "mainCacheManager") as if you have multiple methods where this cacheManager is used it would make sense for those two methods to have their own cacheName each one.

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

    Those 2 different cacheNames inform the cacheManager that there are 2 different namespaces for caches that it should handle and the annotation informs the cacheManager which cacheName relates to this method.