springcachingcaffeine

Individual settings for caches created by @Cacheable


So Spring decided to drop Guava and introduce Caffeine cache support instead. I have the feeling that the support is very limited.

The easiest way to use a cache is with the @Cacheable annotation. A quite common use case is for sure to have multiple caches which have different settings (e.g. long/short lived).

I wasn't able to figure out how to do this. In fact I think it is not possible with the current implementation and this really surprises me.

CaffeineCacheManager is used by Spring to dynamically create caches. It has a few methods to set a Caffeine, a CacheLoader or a CaffeineSpec where you can set the cache properties. However, this is then used for all created caches and I didn't see a way to have properties set for only one cache.

Did I miss anything here?


Solution

  • I solved it like this now. And i created an issue to make this easier here

    public class CustomCaffeineCacheManager extends CaffeineCacheManager {
    
        private Map<String, Cache> preDefinedCaches = new ConcurrentHashMap<>();
    
        public void addCache(String name, Cache cache) {
            preDefinedCaches.put(name, cache);
        }
    
        @Override
        protected Cache<Object, Object> createNativeCaffeineCache(String name) {
            return preDefinedCaches.getOrDefault(name, super.createNativeCaffeineCache(name));
        }
    }
    

    In @Configuration class:

    @Bean
    public CacheManager cacheManager() {
        CustomCaffeineCacheManager caffeineCacheManager = new CustomCaffeineCacheManager();
        caffeineCacheManager.addCache("customCache", Caffeine.newBuilder()
                .expireAfterWrite(2, TimeUnit.MINUTES)
                .maximumSize(5_000).build());
        return caffeineCacheManager;
    }