服务注册与分布式协调 / 系统课时
CuratorCache
CuratorCache
CuratorCache 用来把某个 ZooKeeper 节点及其子树维护成应用内的本地副本,并在节点创建、修改和删除时通知监听器。本节通过一个可运行示例建立缓存、订阅事件、读取最新值,同时说明网络分区下缓存并不等同于完整事件日志。
学习目标
- 使用
CuratorCache缓存指定路径下的节点树 - 监听创建、修改、删除与初始化完成事件
- 通过
get、stream和连接状态理解本地副本的实时性边界
CuratorCache 维护的是什么
默认情况下,CuratorCache 会缓存给定根路径以及下面的整棵节点树;如果只需要单节点缓存,才使用 SINGLE_NODE_CACHE 选项。它要求 ZooKeeper 3.6+,应用启动缓存后可以通过监听器接收节点变化,也可以直接从本地存储读取当前快照。
监听事件只有三种节点变化类型:NODE_CREATED、NODE_CHANGED、NODE_DELETED。初始化完成不是第四种 Type,而是单独的 initialized() 回调,可通过监听器构建器的 forInitialized 注册。

建立缓存并监听节点变化
下面的完整示例假定项目已引入 Curator 5.x 的 curator-framework 与 curator-recipes,并连接 ZooKeeper 3.6+。程序准备 /demo-cache 根节点,启动缓存并等待初始化完成,然后再注册变更监听器,避免把首次装载节点误认为运行期变更。
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;
public class CuratorCacheDemo {
private static final String ROOT = "/demo-cache";
private static final String NODE = ROOT + "/app/name";
public static void main(String[] args) throws Exception {
String connectString = args.length > 0 ? args[0] : "127.0.0.1:2181";
try (CuratorFramework client = CuratorFrameworkFactory.newClient(
connectString, new ExponentialBackoffRetry(1_000, 3))) {
client.start();
if (!client.blockUntilConnected(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("ZooKeeper connection timeout");
}
resetDemoTree(client);
client.create().forPath(ROOT);
client.create().forPath(ROOT + "/app");
try (CuratorCache cache = CuratorCache.build(client, ROOT)) {
CountDownLatch initialized = new CountDownLatch(1);
cache.listenable().addListener(
CuratorCacheListener.builder()
.forInitialized(() -> {
System.out.println("cache=initialized");
initialized.countDown();
})
.build());
cache.start();
if (!initialized.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("CuratorCache init timeout");
}
cache.listenable().addListener((type, oldData, data) -> {
ChildData current = data != null ? data : oldData;
String value = current.getData() == null
? "<empty>"
: new String(current.getData(), StandardCharsets.UTF_8);
System.out.printf("event=%s path=%s value=%s%n",
type, current.getPath(), value);
});
client.create().creatingParentContainersIfNeeded()
.forPath(NODE, "demo-v1".getBytes(StandardCharsets.UTF_8));
waitForValue(cache, NODE, "demo-v1");
client.setData().forPath(
NODE, "demo-v2".getBytes(StandardCharsets.UTF_8));
waitForValue(cache, NODE, "demo-v2");
String cached = cache.get(NODE)
.map(ChildData::getData)
.map(bytes -> new String(bytes, StandardCharsets.UTF_8))
.orElse("<missing>");
System.out.println("cached=" + cached);
client.delete().forPath(NODE);
waitForMissing(cache, NODE);
System.out.println("cached-after-delete=" + cache.get(NODE).isPresent());
}
}
}
private static void resetDemoTree(CuratorFramework client) throws Exception {
try {
client.delete().deletingChildrenIfNeeded().forPath(ROOT);
} catch (KeeperException.NoNodeException ignored) {
// 首次运行时根节点不存在,直接继续创建即可。
}
}
private static void waitForValue(
CuratorCache cache, String path, String expected) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline) {
String value = cache.get(path)
.map(ChildData::getData)
.map(bytes -> new String(bytes, StandardCharsets.UTF_8))
.orElse(null);
if (expected.equals(value)) {
return;
}
Thread.sleep(50);
}
throw new IllegalStateException("cache value timeout: " + expected);
}
private static void waitForMissing(CuratorCache cache, String path) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline) {
if (!cache.get(path).isPresent()) {
return;
}
Thread.sleep(50);
}
throw new IllegalStateException("cache delete timeout: " + path);
}
}预期输出会包含初始化、创建、修改、删除和本地读取。事件回调与主线程输出的先后可能因调度略有差异,但更新后必须读到 demo-v2,删除后缓存中必须不再存在该节点。
cache=initialized
event=NODE_CREATED path=/demo-cache/app/name value=demo-v1
event=NODE_CHANGED path=/demo-cache/app/name value=demo-v2
cached=demo-v2
event=NODE_DELETED path=/demo-cache/app/name value=demo-v2
cached-after-delete=false把事件通知和本地读取分开使用
监听器适合驱动“发生变化后做什么”,例如刷新业务配置、使本地对象失效或记录变更;cache.get(path) 更适合请求线程直接读取某个节点的当前副本。需要遍历整棵子树时可使用 cache.stream(),而 cache.size() 可以快速检查当前缓存条目数量。
ChildData 保存路径、数据和 ZooKeeper Stat。对于删除事件,新数据可能不存在,因此处理通用监听器时应像示例一样优先使用 data,为空时再读取 oldData,避免删除节点时发生空指针错误。
不要把缓存当成事件审计日志
ZooKeeper 网络分区期间,客户端可能收不到每一次服务端变化,因此 CuratorCache 不能保证逐条事件完整。它会在连接恢复后重新同步缓存,目标是让本地副本重新收敛到当前状态,而不是补发所有缺失事件。
对配置中心、服务元数据等读多写少场景,推荐让业务读取本地缓存,同时结合连接状态监控判断数据是否可能陈旧。这样既能减少每次请求直连 ZooKeeper 的成本,也不会把短暂断连误判成强一致的实时数据。