本篇博客博主为大家带来期待已久的关于ZooKeeper的JavaAPI操作。


一. IDEA环境搭建

1.1 创建一个Maven工程

1.2 添加Porn文件

<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/zookeeper -->
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.10</version>
		</dependency>
</dependencies>

1.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  

二. API操作

前提(测试是否正常连接)

package com.buwenbuhuo.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author 卜温不火
 * @create 2020-04-27 22:01
 * com.buwenbuhuo.zookeeper - the name of the target package where the new class or interface will be created.
 * ZooKeeper0427 - the name of the current project.
 */
public class ZkClient {
    private ZooKeeper zkCli;
    private static final String CONNECT_STRING = "hadoop002:2181,hadoop003:2181,hadoop004:2181";
    private static final int SESSION_TIMEOUT = 2000;

//    @Before
//    public void before() throws IOException {
//        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
//            public void process(WatchedEvent watchedEvent) {
//
//            }
//        });
//    }
    // 此部分为上部分的简写
    @Before
    public void before() throws IOException {
        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, e -> {
            System.out.println("默认回调函数");
        });
    }

    @Test
    public void ls() throws KeeperException,InterruptedException{
        List<String> children = zkCli.getChildren("/",true);
        System.out.println("===========================================");
        for (String child: children){
            System.out.println(child);
        }
        System.out.println("===========================================");

        Thread.sleep(Long.MAX_VALUE);
    }
}

2.1 创建ZooKeeper客户端


private static String connectString =
 "hadoop002:2181,hadoop003:2181,hadoop004: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();
				}
			}
		});
	}


2.2 创建子节点

// 创建子节点
@Test
public void create() throws Exception {

		// 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型
		String nodeCreated = zkClient.create("/sanguo", "jinlian".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}


2.4 获取子节点并监听节点变化

// 获取子节点
@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);
}

2.5 判断Znode是否存在

// 判断znode是否存在
@Test
public void exist() throws Exception {

	Stat stat = zkClient.exists("/IDEA", false);

	System.out.println(stat == null ? "not exist" : "exist");
}

2.6 基础操作案例

public static void main(String[] args) throws Exception {
        // 初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher)
        ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("事件类型为:" + event.getType());
                System.out.println("事件发生的路径:" + event.getPath());
                System.out.println("通知状态为:" +event.getState());
            }
        });
	zk.create("/myGirls", "性感的".getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE,
		 CreateMode.PERSISTENT);
      zk.close();

2.7 更多实例操作

public static void main(String[] args) throws Exception {
        // 初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher)
        ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("事件类型为:" + event.getType());
                System.out.println("事件发生的路径:" + event.getPath());
                System.out.println("通知状态为:" +event.getState());
            }
        });
    // 创建一个目录节点
 zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE,
   CreateMode.PERSISTENT); 
 // 创建一个子目录节点
 zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(),
   Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
 System.out.println(new String(zk.getData("/testRootPath",false,null))); 
 // 取出子目录节点列表
 System.out.println(zk.getChildren("/testRootPath",true)); 
 // 修改子目录节点数据
 zk.setData("/testRootPath/testChildPathOne","modifyChildDataOne".getBytes(),-1); 
 System.out.println("目录节点状态:["+zk.exists("/testRootPath",true)+"]"); 
 // 创建另外一个子目录节点
 zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), 
   Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
 System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo",true,null))); 
 // 删除子目录节点
 zk.delete("/testRootPath/testChildPathTwo",-1); 
 zk.delete("/testRootPath/testChildPathOne",-1); 
 // 删除父目录节点
 zk.delete("/testRootPath",-1);
 zk.close();
}

API操作比较偏向基础,博主在此把注释写了上去。


ZooKeeper快速入门系列(6) | Zookeeper的API操作_ide

  好了,本次本次的分享就到这里,大家有什么疑惑可以在评论区留言或者私信博主哦。
   看 完 就 赞 , 养 成 习 惯 ! ! ! \color{#FF0000}{看完就赞,养成习惯!!!} ^ _ ^ ❤️ ❤️ ❤️
  码字不易,大家的支持就是我坚持下去的动力。点赞后不要忘了关注我哦!