毫无疑问,您已经看到,a 的模式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;
}
}