I would like to enable/disable springboot cache with caffeine cache.
With a property, something like my.property.cache.enabled=true
or my.property.cache.enabled=false
to enable and disable caching.
This is not about runtime enabling/disabling cache.
For instance this code:
@Configuration
@EnableCaching
class ReportCacheConfiguration {
@Bean
CacheManagerCustomizer<CaffeineCacheManager> cacheManagerCustomizer(MeterRegistry registry) {
return cacheManager -> cacheManager.registerCustomCache("report", reportCache());
}
private Cache<Object, Object> reportCache() {
return Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.build()
;
}
}
@Service
public class BookServiceImpl implements BookService {
@Cacheable(cacheNames = "report")
public Book findBook(String isbn) {
//some very expensive network call
//then some very expensive database call
return new Book(...);
}
}
With the code above, especially when the third party network call, or the database is overloaded, the caching is very helpful.
However, there are moments where the third party service or the database is under load, in which case, we want to actually "hit the target and do the expensive thing".
To do so, we currently comment the code, create a new build and redeploy...
@Service
public class BookServiceImpl implements BookService {
//@Cacheable(cacheNames = "report")
public Book findBook(String isbn) {
//some very expensive network call
//then some very expensive database call
return new Book(...);
}
}
//@Configuration
//@EnableCaching
//class ReportCacheConfiguration {
//
// @Bean
// CacheManagerCustomizer<CaffeineCacheManager> cacheManagerCustomizer(MeterRegistry registry) {
// return cacheManager -> cacheManager.registerCustomCache("report", reportCache());
// }
//
// private Cache<Object, Object> reportCache() {
// return Caffeine.newBuilder()
// .expireAfterWrite(1, TimeUnit.MINUTES)
// .build()
// ;
// }
//
//}
This is kinda "dumb" in my opinion.
Is it possible, with some spring configuration, something like springboot.cache.enabled=true
(if that exists) or my own custom property to enable/disable caching?
You can use @ConditionalOnProperty
annotation on your configuration class
@Configuration
@EnableCaching
@ConditionalOnProperty("my.property.cache.enabled")
class ReportCacheConfiguration {
...
}
All configuration file will be not enabled if my.property.cache.enabled
will be not true