Spring @CachePut 用两个键放置相同的值

Spring @CachePut to put the same value with two keys

我正在使用 Spring 和使用 @Cacheable@CachePut 注释的内置缓存。

我的@Service 中有两种方法,一种是在数据库中保存值,另一种是从数据库中获取值。两者都使用缓存。

@CachePut(key = "#code")
MyObject saveMyObject(MyObject o, String code) {
    return dao.save(o);
}

@Cacheable(key = "#code")
MyObject getMyObject(String code) {
    return dao.getMyObject(code);
}

在保存对象时我想把它放在另一个缓存中,例如

@CachePut(key = "'TMP_'.concat(#code)")

但我不能在 saveMyObject 方法上使用两个 @CachePut 注释。

我该怎么办?

您可以使用 org.springframework.cache.annotation.Caching 注释对您的 CachePut 进行分组:

@Caching( put = {
        @CachePut(key = "#code"),
        @CachePut(key = "'TMP_'.concat(#code)")
})
MyObject saveMyObject(MyObject o, String code) {
    return dao.save(o);
}