• Java操作Zookeeper


    maven依赖

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

    程序其它依赖:

    <!-- Logger(log4j2) -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.2</version>
    </dependency>
    <!-- Log4j 1.x API Bridge -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-1.2-api</artifactId>
        <version>2.11.2</version>
    </dependency>
    <!-- SLF4J Bridge -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.11.2</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.6.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    View Code

    API操作代码:

    package com.zhi.test;
    
    import java.util.List;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.zookeeper.CreateMode;
    import org.apache.zookeeper.WatchedEvent;
    import org.apache.zookeeper.Watcher;
    import org.apache.zookeeper.ZooDefs.Ids;
    import org.apache.zookeeper.ZooKeeper;
    import org.apache.zookeeper.data.Stat;
    import org.junit.jupiter.api.AfterAll;
    import org.junit.jupiter.api.BeforeAll;
    import org.junit.jupiter.api.MethodOrderer;
    import org.junit.jupiter.api.Order;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.TestInstance;
    import org.junit.jupiter.api.TestInstance.Lifecycle;
    import org.junit.jupiter.api.TestMethodOrder;
    
    /**
     * Zookeeper操作测试
     * 
     * @author 张远志
     * @since 2020年5月3日14:31:28
     *
     */
    @TestInstance(Lifecycle.PER_CLASS)
    @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
    public class ZookeeperTest {
        private final Logger logger = LogManager.getLogger(this.getClass());
        private ZooKeeper zooKeeper;
        private final String path = "/test";
    
        @BeforeAll
        public void init() throws Exception {
            zooKeeper = new ZooKeeper("192.168.59.131:2181", 60000, new Watcher() {
                public void process(WatchedEvent event) {
                    logger.info("事件类型:{},路径:{}", event.getType(), event.getPath());
                }
            });
        }
    
        /**
         * 添加数据,当路径已经存在时会报错,初始版本号为0。第三个参数是权限控制。 <br>
         * 第四个参数,CreateMode:
         * <li>PERSISTENT:持久化保存
         * <li>PERSISTENT_SEQUENTIAL:持久化保存,并且路径附加一个自动增长的序号
         * <li>EPHEMERAL:临时数据,客户端断开连接时自动删除数据(dubbo就是采用这种机制)
         * <li>EPHEMERAL_SEQUENTIAL:客户端断开连接时自动删除数据,并且路径会附加一个自动增长的序号
         * <li>CONTAINER:
         * <li>PERSISTENT_WITH_TTL:客户端断开连接时自动删除数据,当节点在指定时间没有被修改且没有子目录时,数据会被删除
         * <li>PERSISTENT_SEQUENTIAL_WITH_TTL:客户端断开连接时自动删除数据,路径会附加一个自动增长的序号,且当节点在指定时间没有被修改且没有子目录时,数据会被删除
         */
        @Order(1)
        @Test
        public void create() {
            try {
                String back = zooKeeper.create(path, "这是一个测试".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                logger.info("添加一条数据成功,实际路径:{}", back);
            } catch (Exception e) {
                logger.error("调用create出错", e);
            }
        }
    
        /**
         * 判断路径是否存在,不存在时返回null
         */
        @Order(2)
        @Test
        public void exists() {
            try {
                Stat stat = zooKeeper.exists(path, false);
                logger.info("路径为{}的节点{}存在", path, stat == null ? "不" : "");
            } catch (Exception e) {
                logger.error("调用exists出错", e);
            }
        }
    
        /**
         * 查询数据,路径不存在时会报错
         */
        @Order(3)
        @Test
        public void find() {
            try {
                byte[] bits = zooKeeper.getData(path, false, new Stat()); // 路径不存在时会报错
                String data = new String(bits);
                logger.info("路径{}查询到数据:{}", path, data);
            } catch (Exception e) {
                logger.error("调用getData出错", e);
            }
        }
    
        /**
         * 获取子目录,结果为空时返回一个长度为0的ArrayList
         */
        @Order(3)
        @Test
        public void children() {
            try {
                List<String> list = zooKeeper.getChildren(path, false);
                logger.info("路径{}的子目录有:{}", path, String.join("、", list.toArray(new String[0])));
            } catch (Exception e) {
                logger.error("调用getChildren出错", e);
            }
        }
    
        /**
         * 修改数据,路径不存在时会报错,版本号与存储中不一致时也报错
         */
        @Order(4)
        @Test
        public void udpate() {
            try {
                Stat stat = zooKeeper.exists(path, false);
                if (stat != null) {
                    stat = zooKeeper.setData(path, "这是一个修改测试".getBytes(), stat.getVersion()); // 版本号为-1时不做版本校验
                    logger.info("数据修改成功,原版本号:{},新版本号:{}", stat.getAversion(), stat.getVersion());
                }
            } catch (Exception e) {
                logger.error("调用setData出错", e);
            }
        }
    
        /**
         * 删除节点,路径不存在时报错,版本号不一致时也会报错
         */
        @Order(5)
        @Test
        public void delete() {
            try {
                zooKeeper.delete(path, -1); // -1表示不做版本校验
                logger.info("根据path删除数据成功");
            } catch (Exception e) {
                logger.error("调用delete出错", e);
            }
        }
    
        @AfterAll
        public void destory() throws Exception {
            if (zooKeeper != null) {
                zooKeeper.close();
            }
        }
    }
  • 相关阅读:
    Android SDK镜像的介绍使用
    如何在使用MAMP环境下安装MySQLdb
    MySQL – 导出数据成csv
    CSV
    自己写的一个Yeoman的Generator-Require-Angularjs
    笔记
    PHP
    Intellij IDEA 14的注册机
    nodejs
    Python
  • 原文地址:https://www.cnblogs.com/zhi-leaf/p/12822335.html
Copyright © 2020-2023  润新知