Multiple Caffeine Boot Added to Spring CaffeineCacheManager

I want to add several different ones LoadingCache

to Spring CacheManager

, however I don't see how this is possible with CaffeineCacheManager

. It looks like only one loader is possible to update the content, however I need separate loaders for each cache. Is it possible to add multiple boot caches to the Spring cache manager? If so, how?

CaffeineCacheManager cacheManage = new CaffeineCacheManager();

LoadingCache<String, Optional<Edition>> loadingCache1 = 
            Caffeine.newBuilder()
            .maximumSize(150)
            .refreshAfterWrite(5, TimeUnit.MINUTES)
            .build(test -> this.testRepo.find(test));

LoadingCache<String, Optional<Edition>> loadingCache2 = 
            Caffeine.newBuilder()
            .maximumSize(150)
            .refreshAfterWrite(5, TimeUnit.MINUTES)
            .build(test2 -> this.testRepo.find2(test2));

// How do I add to cache manager, and specify a name?

      

+7


source to share


1 answer


Yes it is possible. Since you need to fine tune each cache, you are probably better off defining them yourself. Let's go back to your example with the next step:

SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
    new CaffeineCache("first", loadingCache1),
    new CaffeineCache("second", loadingCache2)));

      

And then you can use that as usual like



@Cacheable("first")
public Foo load(String id) { ... }

      

If you are using Spring Boot, you can just open a separate cache as beans (sic org.springframework.cache.Cache

) and we will detect them and create them for you SimpleCacheManager

.

Note that this strategy allows you to use the cache abstraction with different implementations. first

could be a caffeine cache and second

another provider's cache.

+12


source







All Articles