spring-boot - @CachePut 不更新缓存
问题描述
我想缓存getText
方法并更新缓存setText
。现在缓存getText
方法有效,但我无法更新值。下面的代码基于Hazelcast的教程。
@Service
public class SlowService {
String text = "Initial value";
@Cacheable("text")
public String getText() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return text;
}
@CachePut(value = "text", key = "#newText + 1")
public String setText(String newText) {
text = newText;
return text;
}
}
如何改进上面的代码以使@CachePut
注释工作?
编辑:尝试添加相同的键:
@Cacheable(value = "text", key = "#someKey")
public String getText() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return text;
}
@CachePut(key = "#someKey")
public String setText(String newText) {
text = newText;
return text;
}
但是得到:
java.lang.IllegalArgumentException:为缓存操作返回空键(也许您在没有调试信息的类上使用命名参数?) Builder[public java.lang.String com.example.demo.SlowService.getText()] caches=[text ] | 键='#someKey' | 密钥生成器='' | 缓存管理器='' | 缓存解析器='' | 条件='' | 除非='' | 同步='假'
解决方案
您需要确保在缓存中缓存的值与使用缓存放置时所引用的键相同。
例如:
假设您正在使用键“hw”缓存文本“Hello world”。您的缓存将保存一个值为“Hello world”的键“hw”。
现在假设您想使用“hw”键将值更新为其他文本。为此,您需要确保您传入的密钥与您传递给缓存该实例的密钥相同,在这种情况下为“hw”。
这样,键“hw”将与它一起保存更新的值。
@Cacheable(value = "text", key = "hw")
public String getText() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return text;
}
@CachePut(key = "hw")
public String setText(String newText) {
text = newText;
return text;
}
推荐阅读
- android-studio - 当带有来自hain文件的搜索过滤器的回收器视图建议在android studio中单击一些文本时如何打开新活动
- ajax - 当我从 Ajax 调用会话变量时无法读取它,但如果我从 ASP.Net 中的控制器调用它,我可以读取它
- javascript - 更新嵌套数组 react.js 中的状态
- c - 从内核空间访问进程堆栈指针
- java - Java SE Embedded 在 Java 10 中是否已停用?
- wordpress - Wordpress 删除 /category/ 标签
- ssh - SSHRC 脚本不工作 > 意外的操作员
- selenium - 如何使用 HTML 代码识别 Selenium 的 Web 元素
- django - Django 复杂模型和嵌套查询
- javascript - 车把多选助手