CuratorFramework
(文档:http://curator.apache.org/curator-framework/index.html)
Framework 是什么?
- Curator是什么?
Curator Framework 是zookeeper的一个high-level API;
- Curator能做什么?
》自动链接管理, 如自动重连等;
》简单的API;
》特殊功能的实现等;如leader选举、共享锁等;
Curator实例创建的两种方式
A:工厂方法
CuratorFrameworkFactory.newClient();
B:使用builder
CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(hosts) .sessionTimeoutMs(sessionTimeout) .connectionTimeoutMs(connectionTimeout) .canBeReadOnly(true) .retryPolicy(new ExponentialBackoffRetry(1000, 100)) .defaultData(null) .build();
创建实例后,要先执行start()方法;
//初始化实例 client.start(); //关闭实例 client.close();
PS: Curator实例是线程安全的,所以应该尽量重用同一个实例;
CuratorFramework API
Curator使用的是流畅表达(fluent style) 的接口风格。
client.create().forPath("/head", new byte[0]); client.delete().inBackground().forPath("/head"); client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child", new byte[0]); client.getData().watched().inBackground().forPath("/test");
Method:
http://curator.apache.org/curator-framework/index.html)
Namespaces
为了防止冲突,可能通过增加namespace的方式相同的path
CuratorFramework client = CuratorFrameworkFactory.builder().namespace("MyApp") ... build(); ... client.create().forPath("/test", data); // node was actually written to: "/MyApp/test"