程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(1)

zookeeper代码实现常用命令 - 雨中散步撒哈拉

发布于2021-05-29 19:58     阅读(887)     评论(0)     点赞(12)     收藏(5)


一、创建项目 1. 添加依赖包,pom文件如下 2. 配置日志文件二、代码实现zk命令 0. 创建连接 2. 创建节点 3. 监听节点变化 4. 判断节点是否存在 5. 测试完整代码

作者:雨中散步撒哈拉
来源:https://liudongdong.top
公众号:雨中散步撒哈拉
备注:欢迎关注公众号,学习技术,一起成长!

文末福利:上百本电子书,等待你的领取v

环境说明:

  1. 服务器为centos7集群

  2. zk为zookeeper-3.4.10.tar.gz版本

  3. jdk为1.8

一、创建项目

1. 添加依赖包,pom文件如下

<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>
<!--
https://mvnrepository.com/artifact/org.apache.zookeeper/zook
eeper -->
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.10</version>
</dependency>
</dependencies>

2. 配置日志文件

资源文件创建日志配置文件log4j.properties

log4j.rootLogger=INFO, stdout 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n 
log4j.appender.logfile=org.apache.log4j.FileAppender 
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

二、代码实现zk命令

0. 创建连接

连接集群ip和对外端口2181,集群映射,已在windows做了配置
hosts文件内容:

图片

代码实现连接:

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Test
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

运行打印结果

图片

image.png

2. 创建节点

创建/idea节点,类型为临时节点

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Before
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

@Test
public void createTest() throws Exception{
    String s = zkClient.create("/idea", "helloworld".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    System.out.println(s);
}

打印结果

图片

image.png

3. 监听节点变化

监控根节点下的子节点变化

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Before
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println(event.getType() + "--" + event.getPath());
            try {
                zkClient.getChildren("/", true);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}


@Test
public void childrenTest() throws Exception{
    List<String> children = zkClient.getChildren("/", true);
    for (String ch : children){
        System.out.println(ch);
    }
    Thread.sleep(Long.MAX_VALUE);
}

在xshell模范添加节点,也可以在代码中模仿添加节点

[zk: localhost:2181(CONNECTED) 0] create -e /java "java"
Created /java
[zk: localhost:2181(CONNECTED) 1] create -e /python "java"
Created /python

打印结果

图片

image.png

4. 判断节点是否存在

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Before
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

@Test
public void exTest() throws Exception{
    Stat exists = zkClient.exists("/test", false);
    System.out.println(exists == null ? "no" : "yes");

}

打印结果

图片

image.png

5. 测试完整代码

package com.example.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class ZKDemo {

    private static final String IPS = "master:2181,slave1:2181,slave2:2181";
    private static final int SESSIONTIMEOUT = 200;
    private ZooKeeper zkClient = null;

    @Before
    public void contectTest() throws Exception{
        zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                /*System.out.println(event.getType() + "--" + event.getPath());
                try {
                    zkClient.getChildren("/", true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            }
        });

        System.out.println("==================");
        System.out.println(zkClient.getState());
        System.out.println("==================");
    }

    @Test
    public void createTest() throws Exception{
        String s = zkClient.create("/idea", "helloworld".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(s);
    }

    @Test
    public void childrenTest() throws Exception{
        List<String> children = zkClient.getChildren("/", true);
        for (String ch : children){
            System.out.println(ch);
        }
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void exTest() throws Exception{
        Stat exists = zkClient.exists("/test", false);
        System.out.println(exists == null ? "no" : "yes");

    }


}

文末福利

包含c、c++、java、python、linux、html、php等上百本电子书!

图片

图片

图片

获取方式:

搜索并关注公众号:雨中散步撒哈拉

回复关键词:001

原文链接:https://blog.csdn.net/liu_dongdong55/article/details/117334427



所属网站分类: 技术文章 > 博客

作者:码神

链接:http://www.javaheidong.com/blog/article/207212/fae608c169dd004909c3/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

12 0
收藏该文
已收藏

评论内容:(最多支持255个字符)