Create a Google Guava Cache using a complex key

2019-04-30 05:18发布

I'm trying to create a Cache that has a "Pair" as its key, with that Pair class taken from this post.

I'm trying:

CacheLoader<Pair<String, String>, String> loader =
    new CacheLoader<Pair<String, String>, String>() {
       public String load(Pair<String, String> key) {
           return GetRatingIdentityByShortNameLoader(key.first, key.second);
       }
    };

_ratingIdCache = CacheBuilder.newBuilder()
    .concurrencyLevel(a_conclevel.intValue())
    .maximumSize(a_maxsize.intValue())
    .expireAfterAccess(a_maxage.intValue(), TimeUnit.MINUTES)
    .build(loader);

Which fails to compile in Eclipse (helios, java 1.6) with:

The method build(CacheLoader) in the type CacheBuilder is not applicable for the arguments (new CacheLoader,String>(){})

Does anybody have any suggestions on how to solve this? The objective that that I need to have a cache that stores an "ID" for which the "primary key" is "Rating Agency" + "Rating".

Guava 10.0.1

标签: caching guava
1条回答
2楼-- · 2019-04-30 05:36

I had this cache originally defined as Cache, and when I change the CacheBuilder.build() to use a complex key, I had forgotten to update my cache declaration.

So a simple change from:

Cache<String, String> _ratingAgencyId;

to

Cache<Pair<String, String>, String> _ratingAgencyId;

did the trick.

查看更多
登录 后发表回答