码迷,mamicode.com
首页 > 其他好文 > 详细

ZooKeeper监听服务器节点动态上下线

时间:2021-07-21 17:32:52      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:动态   http   creat   private   zookeeper   class   session   business   打印   

需求

某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。

设计

技术图片

实现

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]

ZooKeeper监听服务器节点动态上下线

标签:动态   http   creat   private   zookeeper   class   session   business   打印   

原文地址:https://www.cnblogs.com/huangjianping/p/15036676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有
迷上了代码!