我按照zk权威指南上的代码创建节点:
package com.zkstudy;
import java.io.IOException;
import java.util.Random;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class Master implements Watcher {
private ZooKeeper zk = null;
private String host;
private String serverId = null;
private boolean isLeader = false;
public Master(String host) {
this.host = host;
Random radom = new Random();
serverId = Integer.toHexString(radom.nextInt());
}
public void start() {
try {
this.zk = new ZooKeeper(host, 15000, this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void createMaster() {
while (true) {
try {
zk.create("/master", serverId.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
isLeader = true;
break;
} catch (KeeperException e) {
e.printStackTrace();
isLeader = false;
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (checkMaster()) {
break;
}
}
}
public boolean checkMaster() {
while (true) {
Stat stat = new Stat();
try {
byte[] data = zk.getData("/master", false, stat);
isLeader = new String(data).equals(serverId);
return true;
} catch (KeeperException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void process(WatchedEvent event) {
System.out.println("watcher thread:---------->" + Thread.currentThread().getId());
System.out.println("event:---------->" + event);
}
public static void main(String[] args) throws InterruptedException {
Master master = new Master("123.206.28.37:2181");
master.start();
master.createMaster();
if (master.isLeader) {
System.out.println("i am master");
}
System.out.println("main thread:---------->" + Thread.currentThread().getId());
Thread.sleep(5000);
}
}
然后我运行了两遍。出现了如下问题:
watcher thread:---------->10
event:---------->WatchedEvent state:SyncConnected type:None path:null
org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists for /master
main thread:---------->1
at org.apache.zookeeper.KeeperException.create(KeeperException.java:119)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
at org.apache.zookeeper.ZooKeeper.create(ZooKeeper.java:783)
at com.zkstudy.Master.createMaster(Master.java:40)
at com.zkstudy.Master.main(Master.java:83)
提示master节点已经存在。
但是我在命令行里面查看却没有发现master节点:
[zk: localhost:2181(CONNECTED) 10] ls
[zk: localhost:2181(CONNECTED) 11] ls /
[zk, zookeeper]
[zk: localhost:2181(CONNECTED) 12]
请问这是为什么呢?zk使用的是单节点,不是伪集群。
自问自答吧。因为我创建的是临时节点,临时节点在绘画断开以后会自动删除,估计这个 ls / 命令应该是列举的持久节点。