zoukankan      html  css  js  c++  java
  • zookeeper简单实现注册与发现以及其他基本操作

    添加依赖

    <dependency>
       <groupId>org.apache.zookeeper</groupId>
       <artifactId>zookeeper</artifactId>
       <version>3.4.6</version>
    </dependency>
    

    注册

    定义一个参数model

    public class ZookeeperRegisterConnectModel {
        //连接地址(可以多个地址,用逗号分割)
        private String connectString;
        private int sessionTimeout;
    
        public String getConnectString() {
            return connectString;
        }
    
        public void setConnectString(String connectString) {
            this.connectString = connectString;
        }
    
        public int getSessionTimeout() {
            return sessionTimeout;
        }
    
        public void setSessionTimeout(int sessionTimeout) {
            this.sessionTimeout = sessionTimeout;
        }
    
        public ZookeeperRegisterConnectModel(){}
        public ZookeeperRegisterConnectModel(String connectString, int sessionTimeout) {
            this.connectString = connectString;
            this.sessionTimeout = sessionTimeout;
        }
    }
    
    

    服务注册具体代码:

    public class ZookeeperRegisterNodeServiceImpl implements IRegisterNodeService, Closeable {
    
        private ZooKeeper zk;
    
        /**
         * 实例连接zookeeper
         *
         * @param zookeeperConnectModel
         * @throws IOException
         */
        public ZookeeperRegisterNodeServiceImpl(ZookeeperRegisterConnectModel zookeeperConnectModel) throws IOException {
            //创建一个与ZooKeeper服务器的连接
            zk = new ZooKeeper(zookeeperConnectModel.getConnectString(), zookeeperConnectModel.getSessionTimeout(), new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
    
                }
            });
        }
    
        /**
         * 创建节点
         *
         * @param service 服务接口名称
         * @param address 服务发布的地址和端口
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        public String createNode(String service, String address) throws KeeperException, InterruptedException {
            Stat stat = zk.exists("/" + service, false);
            //不存在就创建根节点
            if (stat == null) {
                zk.create("/" + service, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            //创建一个子节点
            return zk.create("/" + service + "/" + address, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }
    
        @Override
        public void close() {
            try {
                zk.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    发现

    服务发现具体代码:

    public class ZookeeperGetChildrenServiceImpl implements IGetChildrenService , Closeable {
    
        private ZooKeeper zk;
    
        public ZookeeperGetChildrenServiceImpl(ZookeeperFindConnectModel zookeeperConnectModel) throws IOException {
            //创建一个与ZooKeeper服务器的连接
            zk = new ZooKeeper(zookeeperConnectModel.getConnectString(), zookeeperConnectModel.getSessionTimeout(), new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
    
                }
            });
        }
    
        /**
         * 获取路径下所有节点,幷随机返回一个节点的信息
         * @param path
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        @Override
        public String getChildren(String path) throws KeeperException, InterruptedException {
            List<String> childrens = zk.getChildren("/"+path, false);
            if(null==childrens ||childrens.size()==0){
                return null;
            }
            // shuffle 打乱顺序
            Collections.shuffle(childrens);
            return childrens.get(0);
        }
    
        @Override
        public void close() {
            try {
                zk.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    测试

    public class RegisterFindTest {
        private String service = "zookeeperTest";
        boolean error=false;
    
        @Test
        public void findTest() throws InterruptedException, IOException, KeeperException {
            registerTest();
    
            IGetChildrenService getChildrenService = new ZookeeperGetChildrenServiceImpl(new ZookeeperFindConnectModel("192.168.10.200:2181", 5000));
            List<Thread> threads=new ArrayList<>();
            for(int i=0;i<500;i++){
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
    
                            String organization = getChildrenService.getChildren(service);
                            Assert.assertNotNull(service + "服务地址没有找到", organization);
                        } catch (InterruptedException | KeeperException   |AssertionError e) {
                            error=true;
                        }
                    }
                };
                thread.start();
                threads.add(thread);
            }
            threads.forEach(thread -> {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            Assert.assertFalse(error);
        }
    
    
        private void registerTest() throws IOException, KeeperException, InterruptedException {
            IRegisterNodeService registerNodeService = new ZookeeperRegisterNodeServiceImpl(new ZookeeperRegisterConnectModel("192.168.10.200:2181", 18000));
            registerNodeService.createNode(service, "192.168.10.11:1111");
            registerNodeService.createNode(service, "192.168.10.22:2222");
            registerNodeService.createNode(service, "192.168.10.33:3333");
        }
    }
    

    其他基本操作

        /**
         ** 获取节点上面的数据
         ** @param path 路径
         ** @return
         ** @throws KeeperException
         ** @throws InterruptedException
         * 
         */
        public String getData(String path) throws KeeperException, InterruptedException {
            byte[] data = zookeeper.getData(path, false, null);
            if (data == null) {
                return "";
            }
            return new String(data);
        }
        
        /**
         * 设置节点信息
         * @param path 路径
         * @param data 数据
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        public Stat setData(String path,String data) throws KeeperException,InterruptedException{
            Stat stat = zookeeper.setData(path, data.getBytes(), -1);
            return stat;
        }
        
        /**
         * 删除节点
         * @param path
         * @throws InterruptedException
         * @throws KeeperException
         */
        public void deleteNode(String path) throws InterruptedException, KeeperException{
            zookeeper.delete(path, -1);
        }
        
        /**
         * 获取创建时间
         * @param path
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        public String getCTime(String path) throws KeeperException, InterruptedException{
            Stat stat = zookeeper.exists(path, false);
            return String.valueOf(stat.getCtime());
        }
        
        /**
         * 获取某个路径下孩子的数量
         * @param path
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        public Integer getChildrenNum(String path) throws KeeperException, InterruptedException{
            int childenNum = zookeeper.getChildren(path, false).size();
            return childenNum;
        }
        
        /**
         * 关闭连接
         * @throws InterruptedException
         */
        public void closeConnection() throws InterruptedException{
            if (zookeeper != null) {
                zookeeper.close();
            }
        }
    
  • 相关阅读:
    如何让呼吸机用得更好:4款最好用的鼻枕面罩
    睡眠呼吸机的保养步骤
    干货!科学调整桌椅键盘高度和显示器距离,告别办公疲劳!
    羽绒服的选择标准
    为什么有些羽绒服穿一季就不暖和了?
    不想加班开发管理后台了,试试这个 Java 开源项目吧!
    HelloGitHub 月刊最受欢迎的开源项目 Top10(2020 年)
    SonarQube学习(四)- 使用Jenkins集成JaCoCo和SonarQube检查代码测试覆盖率
    解决 Jenkins 安装插件很慢的问题 ( Linux )
    Docker学习(二)- Docker 安装 Jenkins
  • 原文地址:https://www.cnblogs.com/xzy-/p/11136390.html
Copyright © 2011-2022 走看看