简体   繁体   中英

Spring framework + Hazelcast , how to enable/disable cache using @Cacheable annotation

I am using Spring framework and hazelcast cache to cache REST APi at service layer. The api I am caching has @Cacheable annotation with cachename and keygenerator which works fine. I am looking for best way to enable/disable caching using application property or consul property. For that I am trying to pass the property in condition attribute of @Cachable annotation but is not working. With this approach I will end up passing same value in multiple place (wherever I am caching at API level). Is there any good way to handle such operation. As an example here is a code snippet

@Cacheable(cacheNames = CacheName.MyCache1,keyGenerator = "customKeyGen")
public CachingObject myFirstAPI(String param1, String param2) {
}

Here the hazelcast cache will use customKeyGen and put value (CachingObject) returned by myFirstAPI . If I have to disable this operation , my current approach is to pass some value (read from application property) as condition so that it evaluate the flag/condition before creating cache and cache the value only if the condition is true ie cache is enabled, eg

@Cacheable(cacheNames = CacheName.MyCache1,keyGenerator = "customKeyGen", condition="${enableCache}")
public CachingObject myFirstAPI(String param1, String param2) {
}

In my case the expression language I am passing in condition throwing exception , which I will figure out why (It is currently throwing SpelEvaluationException, Property or field 'enableCache' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' )

My question is , is this correct way to enable/disable caching ? Please suggest.

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