简体   繁体   中英

Spring Caching: Enable/Disable Cache via application.properties at runtime

Given I have some cacheable method, is it possible or a good idea to enable/disable its usage in real-time by changing a property in the application.properties file? For example:

My application.properties file has: UseBookCache=true

@Cacheable(cacheNames="books", condition = "${UseBookCache}")
public Book getByIsbn(String isbn){
    //Return book
}

I want to disable caching during runtime by setting UseBookCache=false

I don't want to disable all caching, only this specific instance. Is this the best way to go about what I need?

I would not recommend to disable this kind of feature at runtime because it will be diffucult to track down what happens (unless you log the configuration and the result) and it quite deeply changes the behaviour of your app.

Annotations' attrubute's value can't be changed at runtime and requires application restart.

Also note that the method will not be called and won't be able to log anything if the cache has an entry for the given parameter.

This annotation can read a parameter value to decide wether or not to use cache. This other SO answer might be of help:

One work around for this You can make your method conditional for cache on the base of parameter. The cache annotations support such functionality through the condition parameter which takes a SpEL expression that is evaluated to either true or false.

 @Cacheable(cacheNames="book", condition="#cached == false") public Book findBook(boolean cached) 

As explained in documentation. https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM