title: Zookeeper实现主从模式
date: 2018-11-12 23:18:40
categories:
- Zookeeper
tags:
- Zookeeper
ZK 探究
native Zookeeper主从模式
Zk的master节点
public class Master implements Watcher{
ZooKeeper zk;
String hostPort;
String serverId = Long.toString(new Random().nextLong()); // 唯一标志节点的随机值
boolean isLeader = false; // 自己是不是主节点? 默认不是主节点
Master(String hostPort) {
this.hostPort = hostPort;
}
void startZK() throws Exception{
zk = new ZooKeeper(hostPort, 5000, this);
}
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent);
}
void stopZK () throws Exception{
zk.close();
}
// 返回是否存在一个master节点
boolean checkMaster() {
while (true) {
try {
Stat stat = new Stat();
byte[] data = zk.getData("/master", false, stat);
System.out.println(new String(data).toString());
System.out.println(serverId);
isLeader = new String(data).equals(serverId);
return true;
} catch (KeeperException | InterruptedException e) {
// 没有master节点 return fasle
return false;
}
}
}
// 回调函数
AsyncCallback.StringCallback masterCreateCallBack = new AsyncCallback.StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
switch (KeeperException.Code.get(rc)) {
// 连接丢失,但我们还要确定master节点是否被创建了,checkMaster
case CONNECTIONLOSS:
checkMaster();
return;
case OK:
isLeader = true;
break;
default:
isLeader = false;
}
System.out.println(KeeperException.Code.get(rc));
System.out.println("我" + (isLeader ? "是" : "不是") + "the leader");
}
}