案例:监听服务器节点动态上下线案例

1.需求
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
2.需求分析

监听服务器节点动态上下线案例_zookeeper

3.具体实现
(0)先在集群上创建/servers节点

create /servers "servers"

Created /servers

(1)客户端监听代码编写

package com.dev1.zkcase;

//当前是监控程序
public class DemoClient {
public static void main(String[] args) throws Exception {
//当前程序有两个功能1,监听 2,打印所有的服务器名称
DemoClient client = new DemoClient();
//1:连接 zk
client.connect();
//2:查询所有节点
client.showServerList();
//3:保持程序运行
client.keepRunning();
}
//3台zk 可以使用的条件是 同学们在hosts文件中做映射ip hostname
//C:\Windows\System32\drivers\etc\hosts
private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";

private void connect() throws Exception {
Watcher watcher = new Watcher() {
public void process(WatchedEvent watchedEvent) {
//如果有人修改servers下面的节点的数据都会执行process
try {
showServerList();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}


};
zk = new ZooKeeper(connectString,sessionTimeout,watcher);//1:连接信息 2 超时信息 3监听器
}
private void showServerList() throws KeeperException, InterruptedException {
//获取servers节点 ls /servers
List<String> children = zk.getChildren(parentNode, true);//参1 节点 参2监听
//创建集合
List<String> servers = new ArrayList<String>();
for(String child:children){
// /servers/server1 get /servers/server1
byte[] data = zk.getData(parentNode + "/" + child, false, null);
servers.add(new String(data));
}
System.out.println(servers);
}
private void keepRunning() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
}

(2)服务器端向Zookeeper写操作实现

package com.dev1.zkcase;


//当前是模拟服务器程序
public class DemoServer {
public static void main(String[] args) throws Exception {
//当前程序有两个功能1,监听 2,打印所有的服务器名称
DemoServer client = new DemoServer();
//1:连接 zk
client.connect();
//2:到servers下面创建子节点
client.createNode(args[0]);
//3:保持程序运行
client.keepRunning();
}
//3台zk 可以使用的条件是 同学们在hosts文件中做映射ip hostname
//C:\Windows\System32\drivers\etc\hosts
private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";

private void connect() throws Exception {
Watcher watcher = new Watcher() {
public void process(WatchedEvent watchedEvent) {
//当前不是监控程序,只是模拟上线
}


};
zk = new ZooKeeper(connectString,sessionTimeout,watcher);//1:连接信息 2 超时信息 3监听器
}
private void createNode(String hostname) throws KeeperException, InterruptedException {
//create /servers/server1 "server1"
System.out.println(hostname+" 上线了");
zk.create(parentNode+"/"+hostname,hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
}
private void keepRunning() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
}