简体   繁体   English

Spring Framework + Hazelcast,如何使用@Cacheable注释启用/禁用缓存

[英]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. 我正在使用Spring框架和hazelcast缓存在服务层缓存REST APi。 The api I am caching has @Cacheable annotation with cachename and keygenerator which works fine. 我正在缓存的api具有@Cacheable批注,其中带有cachename和keygenerator效果很好。 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. 为此,我试图通过@Cachable注释的condition属性中的属性,但是不起作用。 With this approach I will end up passing same value in multiple place (wherever I am caching at API level). 通过这种方法,我最终将在多个地方传递相同的值(无论我在API级别进行缓存的地方)。 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 . 在这里,hazelcast缓存将使用customKeyGen和myFirstAPI返回的put值(CachingObject)。 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' ) 在我的情况下,我要传递条件抛出异常的表达式语言,我会弄清楚为什么(当前正在抛出SpelEvaluationException,属性或字段'enableCache'不能在'org.springframework.cache.interceptor.CacheExpressionRootObject类型的对象上找到)

My question is , is this correct way to enable/disable caching ? 我的问题是,这种启用/禁用缓存的正确方法是吗? Please suggest. 请提出建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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