zookeeper 服务器动态上下线感知

来源:互联网 发布:2016年房地产投资数据 编辑:程序博客网 时间:2024/05/16 02:38

服务端

package com.asin.zk;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooDefs.Ids;import org.apache.zookeeper.ZooKeeper;public class DistributeServer {private static final String HOSTS = "h1:2181,h2:2181,h3:2181";private static final String parentPath = "/servers";private static final int session_time_out = 2000;private static ZooKeeper zk = null;public static void main(String[] args) throws Exception {connect();registServer(args[0]);opearte();}public static void connect() throws Exception {zk = new ZooKeeper(HOSTS, session_time_out, new Watcher() {public void process(WatchedEvent event) {System.out.println(event.getType() + "---" + event.getPath());try {zk.getChildren("/", true);} catch (Exception e) {e.printStackTrace();}}});}public static void registServer(String hostname) throws Exception {String create = zk.create(parentPath + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);System.out.println(create);}public static void opearte() throws Exception {System.out.println("Server处理中。。。");Thread.sleep(Integer.MAX_VALUE);}}

客户端
package com.asin.zk;import java.util.ArrayList;import java.util.List;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;public class DistributeClient {private static final String HOSTS = "h1:2181,h2:2181,h3:2181";private static final String parentPath = "/servers";private static final int session_time_out = 2000;private static ZooKeeper zk = null;public static void main(String[] args) throws Exception {connect();opearte();}public static void connect() throws Exception {zk = new ZooKeeper(HOSTS, session_time_out, new Watcher() {public void process(WatchedEvent event) {System.out.println(event.getType() + "---" + event.getPath());try {getServerList();  //获取有哪些节点} catch (Exception e) {e.printStackTrace();}}});}public static void getServerList() throws Exception {ArrayList<String> list = new ArrayList<String>();List<String> children = zk.getChildren(parentPath, true);for (String child : children) {byte[] data = zk.getData(parentPath + "/" + child, false, null);list.add(new String(data));}System.out.println(list);}public static void opearte() throws Exception {System.out.println("Client处理中。。。");Thread.sleep(Integer.MAX_VALUE);}}
效果就在客户端获取事件通知后,再次获取目录,可以列出最新的节点。



阅读全文
0 0