我是Guava的新手,我想返回逗号分隔的用户列表,本质上是一个String。我正在使用一个第三方API来获取列表。我想缓存该列表,并在用户查询时返回整个列表。

我在网上看了几个示例,它们使用LoadingCache<k, v> and CacheLoader<k,v>。我没有第二个参数,用户名是唯一的。我们的应用程序将不支持对用户的单个查询

/我可以按LoadingCache的格式进行操作吗?就像是

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

最佳答案

毫无疑问,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;
     }
 }

关于java - 使用Google Guava获取列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41188600/

10-11 02:38