动态感知zookeeper节点上下线client端监控server端节点上线情况

package bigdata.zkdist;


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 Client {
private static final String connectString="192.168.15.115:2181";

private static final int sessionTimeout=15000;

private static final String parentNode= "/servers";

private ZooKeeper zk= null;

private  volatile List serviceList;


// 获取zk连接
public void getconnect() throws Exception{
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

@Override
public void process(WatchedEvent event) {
try {
//回调函数,节点发生改变后调用此函数
getList();

} catch (Exception e) {
e.printStackTrace();
}
}
});

}


//获取节点列表
public void getList() throws Exception, Exception{

List arrayList = new ArrayList();

List children = zk.getChildren(parentNode, true);

for (String child : children) {

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

String string = new String(data);

arrayList.add(string);

}

serviceList=children;

System.out.println(serviceList.toString());
}




// 启动业务功能
public void start() throws Exception{
System.out.println("监听成功");

Thread.sleep(Long.MAX_VALUE);

System.out.println(Long.MAX_VALUE);

}



public static void main(String[] args) throws Exception {
//获取连接
Client client = new Client();

client.getconnect();


//获取节点列表
client.getList();

// 启动业务功能
client.start();


}

}

你可能感兴趣的:(动态感知zookeeper节点上下线client端监控server端节点上线情况)