首页 > 解决方案 > @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' | 密钥生成器='' | 缓存管理器='' | 缓存解析器='' | 条件='' | 除非='' | 同步='假'

标签: spring-boot

解决方案


您需要确保在缓存中缓存的值与使用缓存放置时所引用的键相同。

例如:

假设您正在使用键“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;
}

推荐阅读