間違いなく見てきたように、 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;
}
}