1. 程式人生 > >zookeeper動態上下線感知系統

zookeeper動態上下線感知系統

需求---->
某分散式系統當中,祝節點有多臺,可以進行動態上下線,當有任何一臺機器發生了動態的上下線,任何一臺客戶端都能感知得到。

思路---->
1、建立客戶端與服務端
2、啟動client 監聽
3、啟動server 註冊
4、當server端 發生上下線
5、client都能感知的到


public class ZKServer{
	public static void main(String[] args){
		ZKServer zkServer = new ZKServer();
		//1、連線zkServer
		zkServer.getConnect();

		//2、註冊節點資訊 伺服器IP新增到zk中
		zkServer.regist(args[0]);

		//3、業務邏輯處理
		zkServer.bulid(args[0])
	}

	private String connectString="ip1:2181,ip2:2181,ip3:2181";
	private int sessionTimeout = 3000;
	ZooKeeper zkCli = null;
	//定義父jiedian
	private String parentNode = "/servers";

	//連線zkServer
	public void getConnect() throws Exception{

		zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
			@Override
			public void process(WatchedEvent event){

			}
		});
	}

	//註冊資訊
	public void regist(String hostname){
		zkCli.create(parentNode + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		System.out.println(node);
	}

	//構造伺服器
	public void build(String hostname) throws InterruptException{
		System.out.println(hostname+":伺服器上線了");

		Thread.sleep(Long.MAX_VALUE);
	}
}
//客戶端
public class ZkClient{
	main{
		//1、獲取連結
		ZkClient zkClient = new ZkClient();
		zkClient.getConnetc();

		//2、監聽服務的節點資訊
		zkClient.getServers();

		//3、業務邏輯(一直監聽)
		zkClient.getWatch();
	}
	private String connectString="ip1:2181,ip2:2181,ip3:2181";
	private int sessionTimeout = 3000;
	ZooKeeper zkCli;

	public void getConnetc() throws KeeperException, InterruptException {
		zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
			@Override
			public void process(WatchedEvent event){
				List<String> children ;
				try{
					//監聽父節點
					children = zkCli.getChildren("/servers", true);

					//建立集合儲存伺服器列表
					ArrayList<String> serverList = new ArrayList<String>();

					//獲取每個節點的資料
					for(String c: children){
						byte[] data = zkCli.getData("/servers"+c, true, null);
						serverList.add(new String(data));
					}

					//列印伺服器列表
					System.out.println(serverList);

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

	public void getServers(){
		List<String> chidren = zkCli.getChildren("/servers", true);

		//建立集合儲存伺服器列表
		ArrayList<String> serverList = new ArrayList<String>();

		//獲取每個節點的資料
		for(String c: children){
			byte[] data = zkCli.getData("/servers"+c, true, null);
			serverList.add(new String(data));
		}
		//列印伺服器列表
		System.out.println(serverList);
	}

	public void getWatch() throws InterruptException{
		Thread.sleep(Long.MAX_VALUE);
	}
}