使用 Google Guava 获取列表

Using Google Guava to get List

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

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

有什么 / I can twik 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;
     }
 }