gpt4 book ai didi

java - 如何让LoadingCache以非阻塞方式调用load()?

转载 作者:行者123 更新时间:2023-11-30 04:07:09 27 4
gpt4 key购买 nike

我正在使用 Google 的 guava 库来创建我的缓存。我将使用 LoadingCache 接口(interface)。下面是代码片段,

public class BlockedURLs {
private static final long MAX_SIZE = 1000;
private static final long CACHE_DURATION = 2;

private static LoadingCache<String, ArrayList<String> > lruBlockedURLCache;

BlockedURLs() {
lruBlockedURLCache = CacheBuilder
.newBuilder()

.maximumSize(MAX_SIZE)

.expireAfterWrite(CACHE_DURATION, TimeUnit.HOURS)

.build(new CacheLoader<String, ArrayList<String>>() {
@Override
public ArrayList<String> load(String s) throws Exception {
return BlockedURLLoader.fetchBlockedURLListFromRedis(s);
}

});
}

public static ArrayList<String> getBlockedURLList(String domain) {
return lruBlockedURLCache.getUnchecked(domain);
}
}

据我了解,如果我为未缓存列表的域调用 getBlockedURLList ,它将首先加载列表,然后返回结果。但是,这不是我想要的行为。

如果缓存中不存在 key ,我希望缓存调用它的加载函数,但我想异步执行。因此,如果 key 不存在,我会说这次我可以在缓存中没有 key 的情况下工作并继续,但我希望下次尝试获取 key 时 key 存在。本质上,我想以非阻塞方式调用 load() 。也就是说,cache.get() 不应等到先从 load() 获取结果。

最佳答案

这是 Caches Explained 中的示例

// Some keys don't need refreshing, and we want refreshes to be done asynchronously. 
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(new CacheLoader<Key, Graph>() {
public Graph load(Key key) { // no checked exception
return getGraphFromDatabase(key);
}

public ListenableFuture<Graph> reload(final Key key, Graph prevGraph) {
if (neverNeedsRefresh(key)) {
return Futures.immediateFuture(prevGraph);
} else {
// asynchronous!
ListenableFutureTask<Graph> task = ListenableFutureTask.create(new Callable<Graph>() {
public Graph call() {
return getGraphFromDatabase(key);
}
});
executor.execute(task);
return task;
}
}
});

关于java - 如何让LoadingCache以非阻塞方式调用load()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20496426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com