1. 程式人生 > >動態感知zookeeper節點上下線client端監控server端節點上線情況

動態感知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<String> 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<String> arrayList = new ArrayList<String>();

List<String> 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();


}

}