[英]Using Google Guava to get List
我是番石榴的新手,我想返回逗号分隔的用户列表,本质上是String 。 我正在使用一个第三方API来获取列表。 我想缓存该列表,并在用户查询时返回整个列表。
我在网上看了几个示例,它们使用LoadingCache<k, v> and CacheLoader<k,v>
。 我没有第二个参数,用户名是唯一的。 我们的应用程序将不支持对用户的单个查询
/我可以twitter 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.