abhijitab
abhijitab

Reputation: 151

Spring JCache conditional caching

Does spring's JCache annotation @CacheResult allow conditional caching like Spring's own annotation? e.g.

@Cacheable(cacheNames="book", condition="#name.length < 32", unless="#result.hardback")

I could not find anything in the documentation nor source code.

Upvotes: 3

Views: 498

Answers (2)

pochopsp
pochopsp

Reputation: 1041

For those who use @CacheResult in Spring and are looking for a simple binary condition to enable caching (eg. enabled = true/false), I came up with the following solution:

Suppose you have the following method using @CacheResult annotation

@CacheResult(cacheName = "mycachename")
String timeConsumingMethod(String param){
    // time consuming code
    return result;
}

you can then define a property in your .properties file

cache.isenabled=true

and use it in the class you used to define the CacheManager bean like this:

@Configuration
@EnableCaching
public class CacheConfig {
    @Value("${cache.isenabled}")
    private boolean isCacheEnabled;
    
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("mycachename") {
            @Override
            protected Cache createConcurrentMapCache(final String name) {
                if(!isCacheEnabled) return new NoOpCache(name);

                return new ConcurrentMapCache(
                    name,
                    Caffeine.newBuilder()
                        .expireAfterWrite(Duration.ofDays(1))
                        .maximumSize(200).build().asMap(),
                    false
                );
            }
        };
    }
}

This way, if cache.isenabled is true, you return the "real" cache implemented by ConcurrentMapCache class, and if cache.isenabled is false you return an instance of NoOpCache that can be used to disable caching, as stated in its docs:

A no operation Cache implementation suitable for disabling caching.

Upvotes: 1

Stephane Nicoll
Stephane Nicoll

Reputation: 33151

First of all there is no "Spring's JCache annotation". And, no, the standard javax.cache.CacheResult annotation has no support for conditional caching.

You should basically chose the annotation types you're going to use based on the features that you want to use. You "can" use both in the same project if you want but we strongly recommend not to mix/match them on the same cache.

Upvotes: 4

Related Questions