Spring Boot @Cacheable - 如何检查对象是否存在于缓存中而不存储它

问题描述 投票:0回答:1

我在 Spring Boot 中启用了一个简单的缓存来存储对象

@SpringBootApplication
@EnableCaching
public class Application {
    ...
}

以及组件/方法

@Component
public class MyObjectCache {
    @Cacheable(cacheNames = "myObjectCache", key = "#key", sync = true)
    public MyObject findObject(String key) {
        // logic
        return myObject;
    }
}

@Cacheable
想要存储该对象(如果它不存在),并要求我在
// logic
部分创建一个新对象,但我需要一种方法来检查该对象是否存在,因为我在集合中创建了它通过另一个
@CachePut
方法来处理外部用例,当我实际需要存储对象时我会调用该方法。

@CachePut(cacheNames = "myObjectCache", key = "#myObject.id")
public MyObject update(MyObject obj) {
    // do stuff
    return obj;
}

如何仅检查缓存中的键/对象是否存在而不尝试存储新的?我觉得这是一个需要支持的常见用例(至少以一种简单的方式)。

java spring-boot caching
1个回答
0
投票

这是我使用的适合我的解决方案:

@Cacheable(cacheNames = "myObjectCache", key = "#key")
public MyObject findObject(String key, MyObject object) {

    // to see if object is in cache, pass in null for the object
    // with the key you're checking and throw an exception.
    // If the object is already in the cache for the desired key,
    // it will be returned without this method body being executed
    // If not, an exception is thrown here
    if (object == null) {
        throw new IllegalArgumentException("Object not in cache");
    }

    // I pass the cached object in as the 2nd parameter 
    // and it is placed in cache on initial call
    return myObject;
}

然后,对于对象不在缓存中的情况,只需在调用方法中处理异常即可。

© www.soinside.com 2019 - 2024. All rights reserved.