java 使用没有加载功能的番石榴缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13532978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:07:00  来源:igfitidea点击:

using guava cache without a load function

javacachingguava

提问by Mike W

My java app has a cache, and I'd like to swap out the current cache implementation and replace it with the guava cache.

我的 java 应用程序有一个缓存,我想换出当前的缓存实现并用番石榴缓存替换它。

Unfortunately, my app's cache usage doesn't seem to match the way that guava's caches seem to work. All I want is to be able to create an empty cache, read an item from the cache using a "get" method, and store an item in the cache with a "put" method. I do NOT want the "get" call to be trying to add an item to the cache.

不幸的是,我的应用程序的缓存使用似乎与番石榴缓存的工作方式不匹配。我想要的只是能够创建一个空缓存,使用“get”方法从缓存中读取一个项目,并使用“put”方法将一个项目存储在缓存中。我不希望“get”调用试图将项目添加到缓存中。

It seems that the LoadingCache class has the get and put methods that I need. But I'm having trouble figuring out how to create the cache without providing a "load" function.

似乎 LoadingCache 类具有我需要的 get 和 put 方法。但是我无法弄清楚如何在不提供“加载”功能的情况下创建缓存。

My first attempt was this:

我的第一次尝试是这样的:

LoadingCache<String, String> CACHE = CacheBuilder.newBuilder().build();

But that causes this compiler error: incompatible types; no instance(s) of type variable(s) K1,V1 exist so that Cache conforms to LoadingCache

但这会导致此编译器错误:不兼容的类型;不存在类型变量 K1,V1 的实例,因此 Cache 符合 LoadingCache

Apparently I have to pass in a CacheLoader that has a "load" method.

显然我必须传入一个具有“加载”方法的 CacheLoader。

(I guess I could create a CacheLoader that has a "load" method that just throws an Exception, but that seems kind of weird and inefficient. Is that the right thing to do?)

(我想我可以创建一个 CacheLoader,它有一个“加载”方法,它只会抛出一个异常,但这看起来有点奇怪和低效。这是正确的做法吗?)

回答by JB Nizet

CacheBuilder.build()returns a non-loading cache. Just what you want. Just use

CacheBuilder.build()返回一个非加载缓存。正是你想要的。只需使用

Cache<String, String> cache = CacheBuilder.newBuilder().build();