服务器动态上下线监听
命令行客户端中删除所有测试时使用的节点,并创建servers节点
创建net.loftiest.case1.DistributeServer类,即服务端
public class DistributeServer {
private ZooKeeper zK;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeServer server = new DistributeServer();
// 连接zk
server.getConnect();
//注册服务器到zk集群
server.regist(args[0]);
// 启动业务逻辑
server.business();
}
private void business() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);//睡眠java允许的最长时间
}
private void regist(String hostname) throws InterruptedException, KeeperException {
zK.create("/servers/"+hostname,hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);//创建上线服务器的节点 临时带序号
System.out.println(hostname+"is online");
}
private void getConnect() throws IOException {
String connectString = "Hadoop003:2181,Hadoop004:2181,Hadoop005:2181";
int sessionTimeout=2000;
zK = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
}
给server服务端创建三个方法,getConnect(),regist(args[0]),business();
- 连接到zk
- 创建节点
- 线程休眠
创建net.loftiest.case1.DistributeClient类,即客户端
public class DistributeClient {
private ZooKeeper zK;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeClient client = new DistributeClient();
//获取zk连接
client.getConnect();
//监听 /servers下面的节点增加和删除
client.getServerList();
//业务逻辑
client.business();
}
private void business() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
private void getServerList() throws InterruptedException, KeeperException {
List<String> children = zK.getChildren("/servers", true);//获取所有servers下的节点
ArrayList<Object> servers = new ArrayList<>();
for (String child : children) {//子节点data添加到list
byte[] data = zK.getData("/servers/"+child,false,null);
servers.add(new String(data));
}
System.out.println(servers);
}
private void getConnect() throws IOException {
String connectString = "Hadoop003:2181,Hadoop004:2181,Hadoop005:2181";
int sessionTimeout = 2000;
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();
}
}
});
}
}
给客户端创建三个方法,getConnect(),getServerList(),business();
1.连接到zk
2.获取节点信息
3.线程休眠
测试:
命令行创建servers
启动API客户端
命令行在servers下创建新节点
观察到,api客户端中新节点信息动态更新
命令行中删除servers中的新节点
启动API服务端
在服务端的cfg中添加变量Hadoop003,表示Hadoop003上线,即在servers下创建节点
观察到客户端中Hadoop003节点信息动态更新
通过更改变量,观察到节点动态上下线