总体预览
服务器注册
1.获取zk连接
2.注册服务器到zk集群(其实就是在对应的节点下面创建节点)
3.启动业务逻辑(这里是睡觉)
package com.atguigu.zk.case1;
import org.apache.zookeeper.*;
import java.io.IOException;
public class DistributeServer {
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int sessionTimeout = 2000;
private ZooKeeper zooKeeper = null;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
//创建对象
DistributeServer ds = new DistributeServer();
//1.获取zk连接
ds.getConnect();
//2.注册服务器到zk集群
ds.registServer(args[0]);
//3.启动业务逻辑(这里是睡觉)
ds.business(args[0]);
}
//1.获取zk连接
public void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
//2.注册服务器
//其实就是在对应的节点下面创建节点
public void registServer(String hostname) throws InterruptedException, KeeperException {
//创建节点
zooKeeper.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + " is working . . .");
}
//3.业务执行
public void business(String hostname) throws InterruptedException {
System.out.println(hostname + " is working . . .");
Thread.sleep(Long.MAX_VALUE);
}
}
客户端监听
1.建立连接
2.对节点进行监听
3.执行对应业务
package com.atguigu.zk.case1;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DistributeClient {
private ZooKeeper zk = null;
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int sessionTimeout = 2000;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeClient dc = new DistributeClient();
//1.建立连接
dc.getConnect();
//2.对节点进行监听
dc.getServerList();
//3.执行业务
dc.business();
}
//业务流程
private void business() throws InterruptedException {
System.out.println("client is working . . .");
Thread.sleep(Long.MAX_VALUE);
}
//监听节点
private void getServerList() throws InterruptedException, KeeperException {
//1.对父节点进行监听,并获取子节点
List<String> children = zk.getChildren("/servers", true);
ArrayList<String> hostnames = new ArrayList<>();
//2.遍历所有节点,获取主机名称信息,并添加到数组中
for (String child : children) {
byte[] data = zk.getData("/servers/" + child, false, null);
hostnames.add(new String(data));
}
System.out.println(hostnames);
}
//建立连接
private void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
try {
getServerList();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
});
}
}