1. 程式人生 > 其它 >ZooKeeper監聽伺服器節點動態上下線

ZooKeeper監聽伺服器節點動態上下線

需求

某分散式系統中,主節點可以有多臺,可以動態上下線,任意一臺客戶端都能實時感知到主節點伺服器的上下線。

設計

實現

public class DistributeServer {

	public static void main(String[] args) throws Exception {
		
		DistributeServer server = new DistributeServer();
		
		// 1 連線zookeeper叢集
		server.getConnect();
		
		// 2 註冊節點
		server.regist(args[0]);
		
		// 3 業務邏輯處理
		server.business();
	}

	private void business() throws InterruptedException {
	
		Thread.sleep(Long.MAX_VALUE);
	}

	private void regist(String hostname) throws KeeperException, InterruptedException {
		
		String path = zkClient.create("/servers/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		
		System.out.println(hostname +"is online ");
		
	}

	private String connectString = "192.168.0.201:2181";
	private int sessionTimeout = 2000;
	private ZooKeeper zkClient;

	private void getConnect() throws IOException {
		
		zkClient = new ZooKeeper(connectString , sessionTimeout , new Watcher() {
			
			@Override
			public void process(WatchedEvent event) {
				try {
					getChlidren();
				} catch (KeeperException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void getChlidren() throws KeeperException, InterruptedException {

		List<String> children = zkClient.getChildren("/servers", true);

		// 儲存伺服器節點主機名稱集合
		ArrayList<String> hosts = new ArrayList<>();

		for (String child : children) {

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

			hosts.add(new String(data));
		}

		// 將所有線上主機名稱列印到控制檯
		System.out.println(hosts);

	}
}

預期結果

192.168.0.103is online 
[192.168.0.105, 192.168.0.103]
[192.168.0.105, 192.168.0.201, 192.168.0.103]
作者:薄荷加冰
出處:https://www.cnblogs.com/huangjianping/
版權:本文版權歸作者和部落格園共有
轉載:本文以學習、研究和分享為主,歡迎轉載和各類爬蟲,但必須在文章頁面明顯位置給出原文連結。 如果文中有不妥或者錯誤的地方還望您指出,以免誤人子弟。如果您有更好的建議,不如留言一起討論,共同進步! 再次感謝您耐心的讀完本篇文章。