package com.mapleleaf.zookeeper.online;
import java.io.IOException; 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;
/** * @author mapleleaf * 小儿科版本 * 使用zookeeper实现服务器动态上下线动态感知分析: * 主要思路是利用zookeeper监听节点和它可以创建临时节点的特点 * 客户端: * 监听父节点 * 服务端 * 启动时向父节点下生成临时子节点,并在子节点里面写入服务器数据信息 */
public class zkOnlineXiaoErKeClient { private static ZooKeeper zk; private static String zkService = "mini1:2181,mini2:2181,mini3:2181"; private static String parentNode = "/servers"; public static void main(String[] args) throws Exception { } public static void initZkCli() throws IOException{ zk=new ZooKeeper(zkService, 3000, new Watcher(){ @Override public void process(WatchedEvent event) { System.out.println(event.getType() + "----" + event.getPath()); try { getChildNode(); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } //获取子节点 //getChildren()方法仅仅监控对应节点直接子目录的一次变化,但是只会监控直接子节点的增减情况,不会监控数据变化情况!若要每次对应节点发生增减变化都被监测到,那么每次都得先调用getChildren()方法获取一遍节点的子节点列表! public static void getChildNode() throws KeeperException, InterruptedException{ //获取子节点并且监听父节点 List<String> childrens = zk.getChildren(parentNode, true); //获取子节点的数据信息 List<String> childDate = new ArrayList<String>(); for (String children : childrens) { byte[] data = zk.getData(parentNode+"/"+children, false, null); childDate.add(new String(data)); } System.out.println(childDate); } private static void handleBussiness() throws InterruptedException { System.out.println("client start working....."); Thread.sleep(Long.MAX_VALUE); } }
|