• 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]
    
  • 相关阅读:
    几种不同风格的Toast
    [置顶] 如何访问web文件夹之外的文件
    30天自制操作系统笔记(九十)
    tomcat install on Linux
    共享内存使用的基本思路和接口
    30天自制操作系统笔记(九十)——源码
    storm单机版安装配置
    新安装XAMPP,phpMyAdmin错误:#1045
    TI-Davinci开发系列之二使用CCS5.2TI Simulator模拟环境调试DSP程序
    ffmpeg的logo, delogo滤镜参数设置
  • 原文地址:https://www.cnblogs.com/huangjianping/p/15036676.html
Copyright © 2020-2023  润新知