Is it possible to set a different specification per cache using caffeine in spring boot?

David picture David · Apr 17, 2018 · Viewed 10.3k times · Source

I have a simple sprint boot application using spring boot 1.5.11.RELEASE with @EnableCaching on the Application Configuration class.

pom.xml

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
 </dependency>
 <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
 </dependency>

application.properties

spring.cache.type=caffeine
spring.cache.cache-names=cache-a,cache-b
spring.cache.caffeine.spec=maximumSize=100, expireAfterWrite=1d

Question

My question is simple, how can one specify a different size/expiration per cache. E.g. perhaps it's acceptable for cache-a to be valid for 1 day. But cache-b might be ok for 1 week. The specification on a caffeine cache appears to be global to the CacheManager rather than Cache. Am I missing something? Perhaps there is a more suitable provider for my use case?

Answer

membersound picture membersound · Feb 7, 2019

This is your only chance:

@Bean
public CaffeineCache cacheA() {
    return new CaffeineCache("CACHE_A",
            Caffeine.newBuilder()
                    .expireAfterAccess(1, TimeUnit.DAYS)
                    .build());
}

@Bean
public CaffeineCache cacheB() {
    return new CaffeineCache("CACHE_B",
            Caffeine.newBuilder()
                    .expireAfterWrite(7, TimeUnit.DAYS)
                    .recordStats()
                    .build());
}

Just expose your custom caches as beans. They are automatically added to the CaffeineCacheManager.