gpt4 book ai didi

java - 谷歌 Guava 检查缓存中的项目

转载 作者:行者123 更新时间:2023-12-02 09:14:37 24 4
gpt4 key购买 nike

我正在尝试在程序上使用谷歌 Guava 缓存,但不太了解它是如何工作的。

我正在加载缓存,然后在稍后阶段我尝试检查缓存中是否存在某个项目,下面的代码不太有效

如果 getIfPresent 不存在,则返回 null,但调用它的负载会因错误而崩溃

线程“main”com.google.common.cache.CacheLoader$InvalidCacheLoadException 中出现异常:CacheLoader 返回键为 null

 private static LoadingCache<String, Image> imageCache
= CacheBuilder.newBuilder()
.build(new CacheLoader<String, Image>() {

@Override
public Image load(String key) throws Exception {
if (getImage(key) != null) {
return getImage(key);
}
return null;
}
});

public static Image getImage(String key) throws ExecutionException {

return imageCache.getIfPresent(key);

}

这意味着我无法像这样检查缓存中是否存在该项目

    try {
readImage = imageCache.get(fileName);
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

if (readImage != null) {


}

有人可以向我解释一下我在这里做错了什么吗?

最佳答案

如果您需要在加载程序中管理空值,请使用 Guava Optional

@Override
public Optional<Image> load(String key) throws Exception {
return Optional.fromNullable(getImage(key));
}

Image getImage(String key) throws ExecutionException {
//your code to get image from database, or other source
return yourCodeToGetImageFromTheSource(key);
}

您的客户端代码可以是:

try {
Optional<Image> imageCached = imageCache.get(fileName);
} catch (ExecutionException e1) {
// TODO error handling
}

if (imageCached.isPresent()) {
Image img = imageCached.get();
} else {
//your code when img is null
}

关于java - 谷歌 Guava 检查缓存中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com