google 番石榴检查缓存中的项目

google guava checking for item in cache

我正在尝试在程序中使用 google 番石榴缓存,但不太了解它是如何工作的。

我正在加载缓存,稍后我将尝试检查缓存中是否存在某个项目,我的以下代码无法正常工作

getIfPresent returns 如果它不存在则为 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) {


    }

谁能给我解释一下我做错了什么?

CacheLoader#load(String) 的 javadoc 状态

Parameters:

  • key the non-null key whose value should be loaded

Returns:

  • the value associated with key; must not be null

Throws:

  • Exception - if unable to load the result

您已将其实现为返回 null,这违反了 CacheLoader 合同。

如果您需要在加载程序中管理空值,请使用 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
}

首先,您不能通过 load 方法 return null。 如果你想检查缓存中是否存在某个键,你可以简单地通过

获取 LoadingCache 中使用的 ConcurrentMap

Map<K,V> imageMap = imageCache.asMap()

并且只需像使用任何其他地图一样使用该地图,即使用地图上的 containsKey 方法来检查是否存在键等等