Zookeeper客户端java代码操作

Zookeeper客户端java代码操作

上篇博客记录了shell命令操作zookeeper集群的方式,这次尝试采用java代码来操作。通过查阅API,发现并不困难。

1. 首先获得客户端与服务器的连接

    //zookeeper客户端
    private ZooKeeper zkCli;
    //连接地址
    private static final String CONNECT_STRING = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    //session过期时间
    private static final int SESSION_TIMEOUT = 2000;

    /**
     * 创建客户端实例对象
     *
     * @throws IOException
     */
    @Before
    public void before() throws IOException {
        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, (event) -> {
            System.out.println("默认的回调函数");
        });
    }

2. 列出根节点下的子节点(非递归)

    @Test
    public void ls() throws KeeperException, InterruptedException {
        List<String> children = zkCli.getChildren("/", e -> {
            System.out.println("自定义回调函数");
        });

        System.out.println("---------------------");
        for (String child : children) {
            System.out.println(child);
        }
        System.out.println("+++++++++++++++++++++");

        Thread.sleep(Long.MAX_VALUE);

    }

3. 在一个节点下创建子节点

    @Test
    public void create() throws KeeperException, InterruptedException {

        //parameter1:创建的节点路径  parameter2:节点的数据 parameter3:节点权限  parameter4:节点类型
        String str = zkCli.create("/idea", "idea2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(str);
        Thread.sleep(Long.MAX_VALUE);
    }

4. 获取指定节点的内容

    @Test
    public void get() throws KeeperException, InterruptedException {
        byte[] data = zkCli.getData("/simon", true, new Stat());
        String str = new String(data);
        System.out.println(str);
    }

5. 给指定节点设置值

    @Test
    public void set() throws KeeperException, InterruptedException {
        Stat stat = zkCli.setData("/simon", "abcd".getBytes(), 1);
        System.out.println(stat.getDataLength());
    }

6. 获取指定节点的状态信息

    @Test
    public void stat() throws KeeperException, InterruptedException {

        Stat exists = zkCli.exists("/ideaa", false);
        if (exists == null) {
            System.out.println("节点不存在");
        } else {
            System.out.println(exists.getDataLength());
        }
    }

7. 删除指定节点

    @Test
    public void delete() throws KeeperException, InterruptedException {
        Stat exists = zkCli.exists("/idea", false);
        if (exists != null) {
            zkCli.delete("/idea", exists.getVersion());
        }
    }

8. 循环注册,动态获取节点的信息。

也就是当节点有任何变化时,就会调用回调函数,动态的显示节点的变化信息。

    @Test
    public void register() throws KeeperException, InterruptedException {
        byte[] data = zkCli.getData("/simon2", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    register();//发生事件,通知的时候在注册一遍,实现了循环调用
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, null);
        System.out.println(new String(data));
    }

    @Test
    public void testRegister() {
        try {
            register(); //调用register()方法,将进程卡住,循环执行register
            Thread.sleep(Long.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

代码很简单易懂,只是有些内部原理还是有些模糊,例如:Stat是什么?zookeeper是怎么监听到节点发生变化的?又是如何将变化通知给客户端的?在之后的博客中将会详细记录。~

原文地址:https://www.cnblogs.com/simon-1024/p/11746171.html

时间: 2024-10-14 00:44:05

Zookeeper客户端java代码操作的相关文章

Java代码操作zookeeper

以下为一个完整JAVA操作Zookeeper项目步骤: 1. 项目中pom.xml中添加需要的依赖jar包信息 <dependencies> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.9</version> </dependency> <

使用Java代码操作 Redis

使用Java代码操作 RedisJedis简介实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis,对于主流语言,Redis都提供了对应的客户端:提供了很多客户端 官方推荐的是Jedis 托管地址:https://github.com/xetorthio/jedis 要使用redis首先得下载pom依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis<

使用java代码操作redis

使用java代码操作redis 查询中使用redis逻辑 redis在增删改查中的使用 1. Java访问redis 2.1 添加依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> 2.2 Java连接redis Jedis j

ZooKeeper客户端命令行操作

ZooKeeper客户端命令行操作 启动服务端 [[email protected] zookeeper-3.4.10]$ bin/zkServer.sh start 查看状态信息 Using config: /opt/module/zookeeper-3.4.10/bin/../conf/zoo.cfg Starting zookeeper ... STARTED [[email protected] zookeeper-3.4.10]$ bin/zkServer.sh status ZooK

Java代码操作HDFS(在/user/root/下面創建目錄)

1.创建HDFS目录并打成jar包 1 package Hdfs; 2 3 import java.io.IOException; 4 import java.net.URI; 5 6 import org.apache.hadoop.conf.Configuration; 7 import org.apache.hadoop.fs.FileSystem; 8 import org.apache.hadoop.fs.Path; 9 /** 10 * 创建HDFS目录 11 * @author S

zookeeper的java api操作

创建会话: Zookeeper(String connectString,int sessionTimeout,Watcher watcher) Zookeeper(String connectString,int sessionTimeout,Watcher watcher,boolean canBeReadOnly) Zookeeper(String connectString,int sessionTimeout,Watcher watcher,long sessionId,byte[]

Java代码操作oracle数据库(JDBC+sevrlet+jsp+html)

1, 注册页面 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

java:redis(java代码操作redis)

1.redis_demo Maven  ItemMapper.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespa

6、rabbitmq&amp;java代码操作

记住四个注解 存: rabbitTemplate.convertAndSend("bw","我要红包"); 取: @Component @RabbitListener(queues="bw") @RabbitHandler 1.依赖 <!-- 这是rabbitmy依赖--> <dependency> <groupId>org.springframework.boot</groupId> <ar