zookeeper 3.4.14版本的常用命令操作

客户端Shell命令操作

节点类型:

创建节点-永久节点

首先启动zookeeper客户端----zkCli.sh -server 主机名:端口号

 

 创建节点-临时节点

 修改节点值

 删除节点

 监听节点的变化

节点内容的变化:

 在另一台节点上修改/sanguo 下的值

扫描二维码关注公众号,回复: 17249789 查看本文章

 就能看到hadoop201节点上监听到变化:

 监听某节点的子节点变化-- ls Path -w  同理

Java Api操作

1 导包

<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.14</version>
</dependency>

2 在main/src/sources 创建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=%5p [%t] - %m%n

3 zookeeper java api测试

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;

import java.io.IOException;
import java.util.List;

public class ZooKeeperDemo {
    static ZooKeeper zooKeeper;
    static String connectionString="hadoop200:2181,hadoop201:2181,hadoop202:2181";
    static int time=4000000;
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

            //连接zookeeper集群
         zooKeeper = new ZooKeeper(connectionString, time, new Watcher() {
             public void process(WatchedEvent watchedEvent) {

             }

        });


        //查看/目录下的节点
        List<String> children = zooKeeper.getChildren("/", false);
        for (String child : children) {
            System.out.print(child+"\t");

        }
        System.out.println();


        //创建一个新节点
        if(zooKeeper.exists("/china",false)==null)//判断该节点是否事先存在,如果已经存在再创建会报错
        {
          zooKeeper.create("/china", "beijing".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        }
        
         //获取节点内容
        byte[] data1 = zooKeeper.getData("/china", false, null);
        System.out.println("/china: "+new String(data1));

        //删除节点
        if(zooKeeper.exists("/CC",false)!=null)
            zooKeeper.delete("/CC",Version.REVISION);
        
        //查看删除后的节点
        List<String> children1 = zooKeeper.getChildren("/", false);
        System.out.println("delete /CC node:");
        for (String child : children1) {
            System.out.print(child+"\t");

        }
        System.out.println();

        //修改节点内容
        zooKeeper.setData("/sanguo","shuguo".getBytes(),-1);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_52135683/article/details/126568220