zookeeper实现HA入门案例
package com.zhileiedu.zk;
import java.util.Random;
import javax.net.ssl.SSLEngineResult.Status;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
public class T {
static String status = "ACTIVE";
public static void main(String[] args) throws Exception {
String connectString = "192.168.23.157:2181,192.168.23.157:2182,192.168.23.157:2183";
ZooKeeper zk = new ZooKeeper(connectString, 5000, null);
String IP = "202.106.29.138";
String port = new Random().nextInt(500)+"";
if(zk.exists("/zk01", new MasterWatcher()) != null) { // 节点已经创建
status = "STANDBY";
} else {
zk.create("/zk01", (IP + ":"+port).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
status = "ACTIVE";
System.out.println("启动active");
}
Thread.sleep(Integer.MAX_VALUE);
}
static class MasterWatcher implements Watcher {
public void process(WatchedEvent e ) {
// TODO Auto-generated method stub
if (e.getType() == EventType.NodeDeleted) {
status = "ACTIVE";
System.out.println("切换为active");
}
}
}
}
技术改变一切