一、✌题目要求
> 动态监视服务器上下线的过程
二、✌代码实现
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); } }
、