1. 程式人生 > >利用zookeeper實現分散式運用伺服器上下線的動態感知-簡單程式

利用zookeeper實現分散式運用伺服器上下線的動態感知-簡單程式

package cn.nyzc.testzk;


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;


public class TestZK02 {

private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
int sessionTimeout = 2000;
ZooKeeper client;
private String parentPath = "/servers";
//執行緒公用,且不允許拷貝到執行緒棧區
private volatile List<String> serversList = new ArrayList<>();


//main方法。當作主執行緒
public static void main(String[] args) throws Exception {
TestZK02 zk02 = new TestZK02();
// 1建立連線
zk02.getConnect();
// 2 獲取/servers下子節點資訊
zk02.getServerList();
// 3 業務程序啟動
zk02.business();
}


// 建立連線
public void getConnect() throws IOException {
client = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
//監聽事件呼叫方法(一個監聽呼叫一次)
@Override
public void process(WatchedEvent event) {
try {
getServerList();
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
});
}

// 獲取/servers下的子節點資訊
public void getServerList() throws KeeperException, InterruptedException {
// 獲取路徑下的所有子節點
List<String> children = client.getChildren(parentPath, true);


List<String> servers = new ArrayList<>();
for (String child : children) {
// 獲取具體子節點的內容
byte[] data = client.getData(parentPath + "/" + child, false, null);
servers.add(new String(data));
}
//把資料裝入到公用集合中
serversList = servers;
System.out.println(serversList);
}


// 業務功能
public void business() throws Exception {
System.out.println("client is working ...");
Thread.sleep(Long.MAX_VALUE);
}


}