zookeeper实现HA入门案例
Posted leigepython
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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");
}
}
}
}
以上是关于zookeeper实现HA入门案例的主要内容,如果未能解决你的问题,请参考以下文章
Spark技术内幕:Master基于ZooKeeper的High Availability(HA)源代码实现
SpringCloud系列四:Eureka 服务发现框架(定义 Eureka 服务端Eureka 服务信息Eureka 发现管理Eureka 安全配置Eureka-HA(高可用) 机制Eur(代码片段