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?
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
.
I converted my initial PR into a separate tiny project.
To start using it just add the latest dependency from Maven Central:
<dependency>
<groupId>io.github.stepio.coffee-boots</groupId>
<artifactId>coffee-boots</artifactId>
<version>2.0.0</version>
</dependency>
Format of properties is the following:
coffee-boots.cache.spec.myCache=maximumSize=100000,expireAfterWrite=1m
If no specific configuration is defined, CacheManager
defaults to Spring's behavior.
来源:https://stackoverflow.com/questions/49885064/is-it-possible-to-set-a-different-specification-per-cache-using-caffeine-in-spri