使用Google Guava获取List

时间:2016-12-16 16:26:57

标签: java guava google-guava-cache

我是Guava的新手,我希望以以逗号分隔的用户列表返回字符串。我正在使用一个第三方API来获取列表。我希望缓存该列表,并在用户查询时返回整个列表。

我在线查看了一些示例,他们使用了LoadingCache<k, v> and CacheLoader<k,v>。我没有任何第二个参数,用户名是唯一的。我们的应用程序不支持对用户进行单独查询

有什么味道/我可以twik LoadingCache这会让我这样做吗?像

这样的东西
LoadingCache<String> 
.. some code .. 
CacheLoader<String> { 
/*populate comma separated list_of_users if not in cache*/ 
return list_of_users
}

1 个答案:

答案 0 :(得分:2)

毫无疑问,LoadingCache的模式是:

 LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
   .maximumSize(1000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   // ... other configuration builder methods ...
   .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

如果您的服务没有获取密钥,那么您可以忽略它,或使用常量。

 LoadingCache<String, String> userListSource = CacheBuilder.newBuilder()
   .maximumSize(1)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   // ... other configuration builder methods ...
   .build(
       new CacheLoader<String, String>() {
         public Graph load(Key key) {
           return callToYourThirdPartyLibrary();
         }
       });

您可以通过将其包装在另一个方法中来隐藏已忽略的键存在的事实:

  public String userList() {
        return userListSource.get("key is irrelevant");
  }

在您的用例中,您感觉不需要Guava缓存的所有功能。它会在一段时间后使缓存失效,并支持删除侦听器。你真的需要这个吗?你可以写一些非常简单的东西,比如:

 public class UserListSource {
     private String userList = null;
     private long lastFetched;
     private static long MAX_AGE = 1000 * 60 * 5; // 5 mins

     public String get() {
        if(userList == null || currentTimeMillis() > lastFetched + MAX_AGE) {
             userList = fetchUserListUsingThirdPartyApi();
             fetched = currentTimeMillis();
        }
        return userList;
     }
 }
相关问题