【Zookeeper】API应用

IDEA环境搭建
1.创建一个Maven工程
2.添加pom文件

	<dependencies>
			<dependency>
				<groupId>junitgroupId>
				<artifactId>junitartifactId>
				<version>RELEASEversion>
			dependency>
			<dependency>
				<groupId>org.apache.logging.log4jgroupId>
				<artifactId>log4j-coreartifactId>
				<version>2.8.2version>
		dependency>
			
			<dependency>
				<groupId>org.apache.zookeepergroupId>
				<artifactId>zookeeperartifactId>
				<version>3.4.10version>
			dependency>
	dependencies>

3.拷贝log4j.properties文件到项目根目录
需要在项目的src/main/resources目录下,新建一个文件,命名为“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  
  1. 创建ZooKeeper客户端
        private static String connectString =
         "hadoop131:2181,hadoop132:2181,hadoop133:2181";
                private static int sessionTimeout = 2000;
                private ZooKeeper zkClient = null;
         
                @Before
                public void init() throws Exception {
         
                zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
         
                                @Override
                                public void process(WatchedEvent event) {
         
                                        // 收到事件通知后的回调函数(用户的业务逻辑)
                                        System.out.println(event.getType() + "--" + event.getPath());
         
                                        // 再次启动监听
                                        try {
                                                zkClient.getChildren("/", true);
                                        } catch (Exception e) {
                                                e.printStackTrace();
                                        }
                                }
                        });
                }
  1. 创建子节点
// 创建子节点
@Test
public void create() throws Exception {
 
        // 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型
        String nodeCreated = zkClient.create("/hadoop", "hadoopTest1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}

查看
在这里插入图片描述
6. 获取子节点并监听节点变化

// 获取子节点
@Test
public void getChildren() throws Exception {
 
		List<String> children = zkClient.getChildren("/", true);
 
		for (String child : children) {
			System.out.println(child);
		}
 
		// 延时阻塞
		Thread.sleep(Long.MAX_VALUE);
}

添加节点
【Zookeeper】API应用_第1张图片
在这里插入图片描述
查看控制台

【Zookeeper】API应用_第2张图片

  1. 判断Znode是否存在
// 判断znode是否存在
@Test
public void exist() throws Exception {
 
	Stat stat = zkClient.exists("/idea", false);
 
	System.out.println(stat == null ? "not exist" : "exist");
}

全部代码

package com.hadoop.zk;

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

import java.util.List;

public class TestZookeeper {
    private static String connectString =
            "hadoop131:2181,hadoop132:2181,hadoop133:2181";
    private static int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;

    @Before
    public void init() throws Exception {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                // 收到事件通知后的回调函数(用户的业务逻辑)
                System.out.println(event.getType() + "--" + event.getPath());
                // 再次启动监听
                try {
                    zkClient.getChildren("/", true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 创建子节点
    @Test
    public void create() throws Exception {
        // 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型
        String nodeCreated = zkClient.create("/hadoop", "hadoopTest1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    // 获取子节点
    @Test
    public void getChildren() throws Exception {
        List<String> children = zkClient.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        // 延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }

    // 判断znode是否存在
    @Test
    public void exist() throws Exception {
        Stat stat = zkClient.exists("/idea", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }

}

你可能感兴趣的:(Zookeeper)