八、编写代码连接Zookeeper集群

  1. 创建一个maven工程

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!-- 服务器上安装的zookeeper版本为 3.6.1 所以这里需要使用对应的客户端版本 -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.6.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  2. 测试代码

    public class TestZookeeper1 {
        //连接的zookeeper集群
        private String connectString = "192.168.150.129:2181,192.168.150.130:2181,192.168.150.131:2181";
        //超时时间
        private int sessionTimeout = 2000;
        private ZooKeeper zooKeeper;
        
        //连接zookeeper集群
        @Test
        public void init() throws IOException {
            //第三个参数为监听器
             zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
    
                }
            });
        }
    }
    
  3. log4j配置 log4j.properties

    log4j.rootLogger = debug ,  stdout
    
    ### 输出到控制台 ###
    log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target = System.out
    log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c:%L - %m%n
    
  4. 运行代码

    在这里插入图片描述

    以上表示连接zookeeper集群成功

  5. 创建一个节点

    /**
         * 创建一个节点
         * @throws KeeperException
         * @throws InterruptedException
         */
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        //访问权限为所有
        //模式为永久模式
        String path = zooKeeper.create("/study", "java".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }
    
    //需要把上面的init()的注解配置为 @Before
    
  6. 获取子节点并监听子节点变化

    /**
         * 获取子节点 并监听子节点的变化
         * @throws KeeperException
         * @throws InterruptedException
         */
    @Test
    public void getChildrenAndWatch() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", true);
        children.forEach(System.out::println);
        TimeUnit.SECONDS.sleep(Long.MAX_VALUE);
    }
    
    
    @Before
    public void init() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("==================== start =====================");
                List<String> children = null;
                try {
                    children = zooKeeper.getChildren("/", true);
                    children.forEach(System.out::println);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("==================== end =====================");
            }
        });
    }
    
  7. 判断ZNode是否存在

    /**
         * 判断指定ZNode是否存在
         * @throws KeeperException
         * @throws InterruptedException
         */
    @Test
    public void existsZNode() throws KeeperException, InterruptedException {
        Stat exists = zooKeeper.exists("/study", false);
        System.out.println(exists);
    }
    
  8. 注意

    如果出现下面这种异常

    在这里插入图片描述

    是因为客户端连接超时了。

    解决的办法是把 sessionTimeout = 2000; 这个值调大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值