我正在尝试创建具有多个参数值的缓存键。
@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id")
private JSONObject getData(String name, String id) throws Exception {
从上面的场景来看,I name 是必填字段,而 id 是可选字段。我想以这样的方式创建 key ,
- 如果 name = "test"且 id = null,则缓存键必须为cache_name_test
- 如果 name = "test"且 id = "2",则缓存键必须为cache_name_test_2
目前,如果参数值中未传递 id,则键会形成类似“cache_name_test_null”的内容
是否可以使用@Cacheable注释创建这样的 key ?
最佳答案
解决方案
这是可行的,但您需要将 2 个 @Cachable 注释包装在 @Caching 注释中。
@Caching(
cacheable = {
@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id", condition = "#id != null"),
@Cacheable(cacheNames = "cache_name_", key = "#name", condition = "#id == null")
}
)
public JSONObject getData(String name, String id) throws Exception {
私有(private)方法注意事项
您正在私有(private)方法上使用@Caching 注释。这是行不通的。这些注释仅适用于从类外部调用的公共(public)方法。请参阅 Stack Overflow 答案:https://stackoverflow.com/a/16899739/2082699
关于java - 当参数值为空时如何在@Cacheable中创建多个缓存键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61284393/