第一个问题。使用计划的执行程序启动定期刷新。
第二个问题。如果您可以从缓存键或先前缓存的值中推断出您的过期策略,则可以以不同的时间间隔刷新您的数据。
based on this:
https://code.google.com/p/guava-libraries/wiki/CachesExplained#Refresh
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.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 (!needsRefresh(key,prevGraph)) {
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;
}
}
});
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleWithFixedDelay(
new Runnable() {
public void run() {
for (Key key : graphs.asMap().keySet()) {
graphs.refresh(key);
}
}
}, 0, UPDATE_INTERVAL, TimeUnit.MINUTES);