在番石榴中,当使用LoadingCache时,CacheLoader被同步调用。但是,我的load()
操作可能需要很长的时间(〜1秒),如果它需要太长时间(> 200 ms)并且异步加载值,我想采取默认操作。带异步加载的LoadingCache
有没有办法做到这一点?或者还有其他方法可以推荐吗?
在番石榴中,当使用LoadingCache时,CacheLoader被同步调用。但是,我的load()
操作可能需要很长的时间(〜1秒),如果它需要太长时间(> 200 ms)并且异步加载值,我想采取默认操作。带异步加载的LoadingCache
有没有办法做到这一点?或者还有其他方法可以推荐吗?
您可以按照正常的方式执行此操作:提交任务以获取缓存值至ExecutorService
,在Future
上调用get(200, MILLISECONDS)
,如果超时则执行其他操作。
例子:
final LoadingCache<Key, Result> cache = ...
final Key key = ...
ExecutorService executor = ...
Future<Result> future = executor.submit(new Callable<Result>() {
@Override public Result call() throws Exception {
return cache.get(key);
}
});
try {
Result result = future.get(200, TimeUnit.MILLISECONDS);
// got the result; do stuff
} catch (TimeoutException timeout) {
// timed out; take default action
}
您可以检查是否值为null与getIfPresent命令。 如果该值为null,则可以提交异步加载值并继续执行流程的任务。
例如:
Map<String, String> map = cache.getIfPresent(key);
if(map == null){
executorService.submit(new Callable<Map<String, String>>() {
@Override
public Map<String, String> call() throws Exception {
return cache.get(key);
}
});
}
else{
continue with the flow...
}
,你也应该使用refreshAfterWrite功能,如果你想刷新缓存中的值,而你还在读旧值实现重载方法。 通过这种方式,缓存将始终更新,读取值的主线程不会受到影响。
例如:
cache = CacheBuilder.newBuilder()
.refreshAfterWrite(30, TimeUnit.SECONDS)
.build(
new CacheLoader<String, Map<String,String>>() {
public Map<String, String> load(String key) throws Exception {
map = hardWork(key)//get map from from DB -- expensive time commend
return map;
}
@Override
public ListenableFuture<Map<String, String>> reload(final String key, Map<String, String> oldValue) throws Exception {
// we need to load new values asynchronously, so that calls to read values from the cache don't block
ListenableFuture<Map<String, String>> listenableFuture = executorService.submit(new Callable<Map<String, String>>() {
@Override
public Map<String, String> call() throws Exception {
//Async reload event
return load(key);
}
});
return listenableFuture;
}
});
我相当肯定有没有办法与当前的API来实现这一目标。 –