參考:從Paxos到Zookeeper分布式一致性原理和實踐
使用的zk依賴是cdh5.16.2的3.4.5
<!-- zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.5-cdh5.16.2</version>
</dependency>
Zk在創建節點的有同步創建和異步創建,但是Zk是不支持遞歸創建節點,即父節點必須存儲。
在創建同名的節點的時候,會拋出NodeExistsException異常。
Zookeeper節點內容只支持字節數組(byte[])
同步創建節點代碼,其中創建了一個永久節點,key是/app1,value是123
package com.bigdata.zookeeper;
import org.apache.zookeeper.*;
import java.util.concurrent.CountDownLatch;
public class ZkExample implements Watcher {
public static CountDownLatch connectedSemaphore = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("master:2181", 5000, new ZkExample());
System.out.println(zk.getState());
try {
connectedSemaphore.await();
String path = zk.create("/app1", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("success create znode: " + path);
} catch (InterruptedException e) {
System.out.println("Zk session established" + e);
}
}
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
connectedSemaphore.countDown();
}
}
}
輸出,使用Zkui查看zk中的數據,能發現多出了/app1的節點,節點的值是123

Zk中節點的類型分為持久節點(PERSISTENT),持久順序節點(PERSISTENT_SEQUENTIAL),臨時節點(EPHEMERAL),臨時順序節點(EPHEMERAL_SEQUENTIAL)
區別如下

異步創建節點代碼,
package com.bigdata.zookeeper;
import org.apache.zookeeper.*;
import java.util.concurrent.CountDownLatch;
public class ZkExample implements Watcher {
public static CountDownLatch connectedSemaphore = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("master:2181", 5000, new ZkExample());
System.out.println(zk.getState());
try {
connectedSemaphore.await();
zk.create("/app2", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT, new IStringCallback(), "This is context");
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
System.out.println("Zk session established" + e);
}
}
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent);
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
connectedSemaphore.countDown();
}
}
}
class IStringCallback implements AsyncCallback.StringCallback {
@Override
public void processResult(int i, String s, Object o, String s1) {
System.out.println("Create path result : [" + i + ", " + s + ", " + o + ", real path name : " + s1);
}
}
如果創建成功,返回的狀態碼是0

如果節點已經存在,返回的狀態碼是-110

具體介紹

