使用Zookeeper监听服务器节点动态上下线案例
一、服务器端代码
package com.hadoop.online;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
/*
服务器端 :一旦运行需要在zookeeper中创建临时节点
思路:
1.创建客户端对象
2.判断servers节点是否存在如果不存在则创建
3.在servers节点上创建临时节点
*/
public class Server {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
//1.创建客户端对象
String server = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
ZooKeeper zooKeeper = new ZooKeeper(server, 4000, new Watcher() {
public void process(WatchedEvent event) {
}
});
//2.判断servers节点是否存在(用来存储服务器信息)
Stat exists = zooKeeper.exists("/servers", false);
if (exists == null){
//节点不存在需要创建(永久节点)
zooKeeper.create("/servers","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
//3.创建临时节点
zooKeeper.create("/servers/"+args[0],args[1].getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
//4.让服务器一直运行
Thread.sleep(Long.MAX_VALUE);
}
}
二、客户端代码
package com.atguigu.online;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.List;
/*
客户端 :用来实时获取正在运行的服务器有哪些
思路:
1.创建客户端对象
2.监听zkooper上的servers节点
3.一旦接收到响应事件则说明节点发生了改变那么再获取该节点的子节点并输出即可
4.关资源
*/
public class client {
public static ZooKeeper zooKeeper = null;
public static void main(String[] args) throws IOException, InterruptedException {
//1.创建客户端对象
String server = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
zooKeeper = new ZooKeeper(server, 4000, new Watcher() {
public void process(WatchedEvent event) {
//2.监听zookeeper上的servers节点
//注意 :servers节点由谁创建? 由服务器创建(也可以由客户端创建,同时操作需要考虑死锁情况)
registeListen();
}
});
//3.不能让主线程死掉
Thread.sleep(Long.MAX_VALUE);
}
/*
*注册监听
*/
public static void registeListen() {
System.out.println("===========================");
try {
List<String> children = zooKeeper.getChildren("/servers", new Watcher() {
public void process(WatchedEvent event) {
//一旦子节点发生改变就会调用此方法
//一旦监听到事件需要再次注册监听(监听方法监听到一个事件后便会失效)
registeListen();
}
});
//输出子节点
for (String child : children) {
System.out.println(child);
}
} catch (Exception e) {
// e.printStackTrace();
//关闭资源
}
}
}
基础配置信息详见:Zookeeper客户端操作(使用IDEA进行编程):https://blog.csdn.net/weixin_42796403/article/details/110005401