0
点赞
收藏
分享

微信扫一扫

ZooKeeper学习:服务器动态上下线案例分析


## ✌✌✌古人有云,好记性不如烂笔头,千里之行,始于足下,每日千行代码必不可少,每日总结写一写,目标大厂,满怀希望便会所向披靡,哈哈哈!!!✌✌✌

ZooKeeper学习:服务器动态上下线案例分析_分布式

一、✌题目要求

> 动态监视服务器上下线的过程

二、✌代码实现

1.✌Server服务器类

public class Server {

private static String connectString = "hadoop151:2181,hadoop152:2181,hadoop153:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;

public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

args = new String[]{"hadoop153"};

Server server = new Server();

server.getConnect();

server.regist(args[0]);

server.business();

}

//连接ZooKeeper集群
private void getConnect() throws IOException {


zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {

}
});
}

//注册服务器,将主机名写入ZooKeeper中
private void regist(String hostname) throws KeeperException, InterruptedException {

String create = zk.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

System.out.println(hostname + " is online" + create);

}

//业务代码
private void business() throws InterruptedException {

//保持代码不结束,监控整个过程
Thread.sleep(Long.MAX_VALUE);

}

}

2.✌Client客户端类

public class Client {

private static String connectString = "hadoop151:2181,hadoop152:2181,hadoop153:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;

public static void main(String[] args) throws InterruptedException, IOException, KeeperException {

Client client = new Client();

client.getConnect();

client.getServerList();

client.business();
}

//连接ZooKeeper,并实现方法
private void getConnect() throws IOException {

zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
try {
getServerList();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}

//获取文件子目录文件
private void getServerList() throws KeeperException, InterruptedException {

List<String> children = zk.getChildren("/servers", true);

ArrayList<String> servers = new ArrayList<>();

for (String child : children) {

byte[] data = zk.getData("/servers/" + child, false, null);

servers.add(new String(data));

}

System.out.println(servers);
}

private void business() throws InterruptedException {

Thread.sleep(Long.MAX_VALUE);

}

}


举报

相关推荐

0 条评论