简体   繁体   English

谷歌番石榴检查缓存中的项目

[英]google guava checking for item in cache

I'm trying to use google guava cache on a program but am not quite getting how it works. 我正在尝试在程序上使用谷歌番石榴缓存,但我不知道它是如何工作的。

I'm loading up the cache and then at a later stage i'm trying to check if an item exists in the cache, my code below doesnt quite work 我正在加载缓存,然后在稍后阶段我正在尝试检查缓存中是否存在某个项目,我的代码下面的代码还不行

The getIfPresent returns null if it doesnt exist but the load which calls it bombs out after with the error 如果getIfPresent不存在,则返回null,但调用它的负载在出错之后会弹出

Exception in thread "main" com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 线程“main”中的异常com.google.common.cache.CacheLoader $ InvalidCacheLoadException:CacheLoader为key返回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);

}

this means i cant check for the presense of the item in the cache like so 这意味着我不能像这样检查缓存中项目的存在

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

    if (readImage != null) {


    }

can someone explain to me what i'm doing wrong here? 谁能向我解释我在这里做错了什么?

If you need manage null values in your Loader, use Guava Optional 如果需要在Loader中管理空值,请使用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);
}

Your client code, can be: 您的客户端代码可以是:

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
}

First Of All you cannot return null from your load method. 首先,您不能从load方法return null If you want check whether a certain key exists in your cache you can simply get the ConcurrentMap used within the LoadingCache through 如果要检查缓存中是否存在某个密钥,可以直接获取在LoadingCache使用的ConcurrentMap

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

And simply use that map as any other map ie use the containsKey method on the Map to check whether a key is present and so on 并简单地将该映射用作任何其他映射,即使用Map上的containsKey方法来检查密钥是否存在等等

The javadoc of CacheLoader#load(String) states CacheLoader#load(String)的javadoc状态

Parameters : 参数

  • key the non-null key whose value should be loaded 键入应加载其值的非null键

Returns : 退货

  • the value associated with key; 与密钥相关的值; must not be null 不能为空

Throws : 抛出

  • Exception - if unable to load the result 例外 - 如果无法加载结果

You've implemented it as returning null , that breaks the CacheLoader contract. 您已将其实现为返回null ,这会破坏CacheLoader合约。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM