使用curator treeCache
时,如何确保缓存已就绪?
在cache.start()
之后,如果我立即调用getCurrentData
,它将返回null
,那么如何确保缓存已准备好?有人可以给我一个例子吗?谢谢
client = CuratorFrameworkFactory.builder()
.connectString(connectionString)
.retryPolicy(new ExponentialBackoffRetry(zkConnectionTimeoutMs, 3))
.sessionTimeoutMs(zkSessionTimeoutMs)
.build();
client.start();
cache = new TreeCache(client, rootPath);
cache.start();
ChildData child = cache.getCurrentData(rootPath); // child is null
Thread.sleep(50); // must sleep for a while
child = cache.getCurrentData(rootPath); // child is ok
最佳答案
您可以为Treecache添加一个监听器,并监听INITIALIZED事件。
Semaphore sem = new Semaphore(0);
client = CuratorFrameworkFactory.builder()
.connectString(connectionString)
.retryPolicy(new ExponentialBackoffRetry(zkConnectionTimeoutMs, 3))
.sessionTimeoutMs(zkSessionTimeoutMs)
.build();
client.start();
cache = new TreeCache(client, rootPath);
cache.start();
TreeCacheListener listener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event)
throws Exception {
switch (event.getType()) {
case INITIALIZED: {
sem.release();
}
}
};
cache.getListenable().addListener(listener);
sem.acquire();
child = cache.getCurrentData(rootPath);