4. 服务器动态上下线监听案例
4.1 需求分析
服务器动态上下线
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fgjrvpYH-1629616974036)(屏幕截图 2021-08-18 164527.png)]
本质上:
- 服务器与客户端1、2…针对于Zookeeper集群来说,都是客户端
- 服务器跟Zookeeper集群打交道的是创建节点:
create( )
操作 - 客户端1、2…跟Zookeeper集群打交道的是监听:
-w
、get
4.2 服务器向集群注册
先在集群上创建/servers 节点:
[zk: localhost:2181(CONNECTED) 10] create /servers "servers" Created /servers [zk: localhost:2181(CONNECTED) 11] ls / [sanguo, servers, zookeeper]
DistributeServer类:
public class DistributeServer {
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int sessionTimeout = 2000;
private ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeServer server = new DistributeServer();
//1.获取zk连接
server.getConnect();
//2.注册服务器到zk集群(将服务器名称作为参数传入)
server.Regist(args[0]);
//3.启动业务逻辑(sleep)
server.business();
}
private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
private void Regist(String hostname) throws InterruptedException, KeeperException {
String server = zooKeeper.create("/servers/"+hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + " is online");
}
private void business() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
}
DistributeClient类:
public class DistributeClient {
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int sessionTimeout = 2000;
private ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeClient Client = new DistributeClient();
//1.获取zk连接
Client.getConnect();
//2.监听/severs下面子节点的增加和删除
Client.getServerList();
//3.业务逻辑(sleep)
Client.business();
}
private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
//监听完成一次后,立刻再监听一次
try {
getServerList();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
});
}
private void getServerList() throws InterruptedException, KeeperException {
List<String> children = zooKeeper.getChildren("/servers", true);
ArrayList<String> servers = new ArrayList<>();
for (String child : children) {
//将获取到的节点名拼接成绝对路径,以此来获取到节点中的数据
byte[] data = zooKeeper.getData("/servers/" + child, false, null);
//将获取到的数据存入集合中
servers.add(new String(data));
}
//打印集合
System.out.println(servers);
}
private void business() throws InterruptedException {
//Thread.sleep(80000);
//客户端在执行业务的同时一直在监听集群
//sleep设置的时间太短会导致获取不到监听
Thread.sleep(Long.MAX_VALUE);
}
}
测试:
-
先执行DistributeClient类,启动客户端
-
执行DistributeServer:
-
mian函数需要先传入参数:传入hadoop102
-
执行DistributeServer:Hadoop102上线
-
-
观察客户端的变化:监听到Hadoop102上线,并打印集合