一. ZkClient
ZkClient是一个在ZooKeeper原生API接口之上进行了包装的开源的ZooKeeper客户端。
1、Maven 引用
<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
2、创建session
public class CreateSessionDemo {
public static void main(String[] args) {
ZkClient zkClient = new ZkClient("127.0.0.1:2181",5000);
System.out.println("ZooKeeper session established");
}
}
3、创建节点
public class CreateNodeDemo {
public static void main(String[] args) {
ZkClient zkClient = new ZkClient("127.0.0.1:2181",5000);
String path = "/zk-test/c1";
zkClient.createPersistent(path,true);
}
}
4、获取子节点
*/
public class GetChildrenDemo {
public static void main(String[] args) throws InterruptedException {
String path = "/zk-test";
ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
zkClient.subscribeChildChanges(path, new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
System.out.println(parentPath + "'s child changed, currentChilds:" + currentChilds);
}
});
zkClient.createPersistent(path);
Thread.sleep(1000);
zkClient.createPersistent(path+"/c1");
Thread.sleep(1000);
zkClient.delete(path+"/c1");
Thread.sleep(1000);
zkClient.deleteRecursive(path);
Thread.sleep(10000);
}
}
5、删除节点
public class DeleteNodeDemo {
public static void main(String[] args) {
ZkClient zkClient = new ZkClient("127.0.0.1:2181",5000);
String path = "/zk-test";
zkClient.deleteRecursive(path);
}
}
二、Curator
Curator是一个在ZooKeeper原生API接口之上进行了包装的开源的提供Fluent风格的ZooKeeper客户端。提供ZooKeeper各种应用场景的抽象封装
1、Maven 引用
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>