0
点赞
收藏
分享

微信扫一扫

zookeeper java API开发服务器动态上下线监控


约定与配置

客户端代码

package com.chen.zk;

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.List;

public class DistributeClient {
private String connectString = "hadoop100:2181,hadoop101:2181,hadoop102:2181";
private int sessionTimeout = 2000;// 2秒
private ZooKeeper zooKeeper;

public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
DistributeClient client = new DistributeClient();
//获取连接
client.getConnect();
//监听服务器节点的子节点增加和删除
client.getServer();
//启动业务逻辑
client.business();
}

private void business() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}

private void getServer() throws KeeperException, InterruptedException {
List<String> children = zooKeeper.getChildren("/server", true);
for (String child : children) {
System.out.println(new String(zooKeeper.getData("/server/" + child, false, null)));
}
System.out.println("----------------------");
}

private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
//监听
public void process(WatchedEvent watchedEvent) {
try {
getServer();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}

服务端代码

package com.chen.zk;

import org.apache.zookeeper.*;

import java.io.IOException;

public class DistributeServer {
private String connectString = "hadoop100:2181,hadoop101:2181,hadoop102:2181";
private int sessionTimeout = 2000;// 2秒
private ZooKeeper zooKeeper;

public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
DistributeServer server = new DistributeServer();
//获取连接
server.getConnect();
//注册服务器到集群
server.regist(args[0]);
//启动业务逻辑
server.business();
}

private void regist(String hostname) throws KeeperException, InterruptedException {
zooKeeper.create("/server/" + 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);
}

private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
//监听
public void process(WatchedEvent watchedEvent) {

}
});
}
}


举报

相关推荐

0 条评论