zoukankan      html  css  js  c++  java
  • java操作zookeeper

    依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.10</version>
        </dependency>
    </dependencies>

    一些api的demo:

    public class TestZookeeper {
    
        // 2181 : 访问 zookeeper集群的端口号
        private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
        private int sessionTimeout = 2000;
        private ZooKeeper zkClient;
    
        @Before
        public void init() throws IOException {
             zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
    
                }
            });
        }
    
        //创建节点
        @Test
        public void create() throws Exception {
    
            // 参数1:要创建的节点的路径;
            // 参数2:节点数据 ;
            // 参数3:节点权限 ;
            // 参数4:节点的类型
            String nodeCreated = zkClient.create("/atguigu", "jinlian".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println(nodeCreated);
        }
    
    
        //创建子节点并监控数据的变化
        @Test
        public void getDataAndWatch() throws Exception {
            List<String> children = zkClient.getChildren("/", false);
    
            for (String s:children){
                System.out.println(s);
            }
    
        }
    
        // 判断znode是否存在
        @Test
        public void exist() throws Exception {
    
            Stat stat = zkClient.exists("/sanguo", false);
    
            System.out.println(stat == null ? "not exist" : "exist");
        }
    }

    【案例】服务器动态节点上下线

    需求:

    某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时

    感受到主服务器节点的上下线

    过程:

    clipboard

    代码实现

    服务器端:将自己的信息注册到zookeeper

    public class DistributeServer {
    
        // 2181 : 访问 zookeeper集群的端口号
        private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
        private int sessionTimeout = 2000;
        private ZooKeeper zkClient;
    
        // 获取与zookeeper集群的连接
        private void getConnect() throws IOException {
            zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
    
                }
            });
        }
    
    
        private void regist(String hostName) throws Exception {
            String path = zkClient.create("/servers/server", hostName.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println(hostName + " is on line!");
    
        }
    
        private void business() throws InterruptedException {
            Thread.sleep(Long.MAX_VALUE); //保证此进程不结束
        }
    
        public static void main(String[] args) throws Exception {
    
            //1.连接服务器集群
            DistributeServer server = new DistributeServer();
            server.getConnect();
            //2.注册节点
            server.regist(args[0]);
    
            //3 业务逻辑
            server.business();
        }
    }

    客户端:监听zookeeper某个节点下,子节点的变化信息

    public class DistrubuteClient {
    
        // 2181 : 访问 zookeeper集群的端口号
        private String connectString = "172.20.10.14:2181,172.20.10.4:2181,172.20.10.5:2181";
        private int sessionTimeout = 2000;
        private ZooKeeper zkClient;
    
        // 获取与zookeeper集群的连接
        private void getConnect() throws IOException {
            zkClient = new ZooKeeper(connectString, 2000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    try {
                        getChildren();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        private void getChildren() throws Exception {
            List<String> children = zkClient.getChildren("/servers", true);
            //存储服务器节点主机名称的集合
            ArrayList<String> list = new ArrayList<>();
            for(String child:children){
                byte[] data = zkClient.getData("/servers/" + child, false, null);
                list.add(new String(data ));
            }
            //将所有主机名称在线打印
            System.out.println(list);
        }
    
        private void business() throws InterruptedException {
            Thread.sleep(Long.MAX_VALUE); //保证此进程不结束
        }
    
        public static void main(String[] args) throws Exception {
            DistrubuteClient client =new DistrubuteClient();
            // 获取连接
            client.getConnect();
            //2.注册监听
            client.getChildren();
    
            client.business();
        }
    }

    这样客户端就能动态的监视服务端主机的变化情况

  • 相关阅读:
    广义后缀自动机模板
    HDU 5852 Intersection is not allowed! ( 2016多校9、不相交路径的方案、LGV定理、行列式计算 )
    BZOJ 4017 小 Q 的无敌异或 ( 树状数组、区间异或和、区间异或和之和、按位计贡献思想 )
    WHU 583 Palindrome ( 回文自动机 && 本质不同的回文串的个数 )
    HDU 5527 Too Rich ( 15长春区域赛 A 、可贪心的凑硬币问题 )
    HDU 5863 cjj's string game ( 16年多校10 G 题、矩阵快速幂优化线性递推DP )
    HDU 5544 Ba Gua Zhen ( 2015 CCPC 南阳 C、DFS+时间戳搜独立回路、线性基 )
    HDU 5734 Acperience ( 数学公式推导、一元二次方程 )
    hihocoder 1251 Today is a rainy day ( 15年北京 C、暴力 )
    HDU 5113 Black And White ( 2014 北京区预赛 B 、搜索 + 剪枝 )
  • 原文地址:https://www.cnblogs.com/houchen/p/13360511.html
Copyright © 2011-2022 走看看