Zookeeper实战API 应用

Posted ZSYL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Zookeeper实战API 应用相关的知识,希望对你有一定的参考价值。

1. IDEA 环境搭建

1.1 创建一个Maven工程

注意Maven的相关配置,以及运行的jdk环境,可以参考我的Maven专栏学习:https://zsyll.blog.csdn.net/article/details/120054137



1.2 添加pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zs</groupId>
    <artifactId>zookeeper</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>

</project>

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 

2. 创建ZooKeeper客户端

private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104: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();
			}
		}
	});
}

3. 创建子节点

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

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

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);
}

5. 判断Znode是否存在

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

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

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

6. 完整代码

package com.zs.zookeeper;

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

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

public class TestZookeeper {

    // 设置连接的哪些集群
    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 2000;
    private Watcher watcher;
    private ZooKeeper zkClient;

    @Before
    public void init() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("---------start----------");
                List<String> children = null;// 获取根目录下所有节
                try {
                    children = zkClient.getChildren("/", false);

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

                    System.out.println("---------end----------");

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 1.创建节点
    @Test
    public void createNode() throws KeeperException, InterruptedException {

        String path = zkClient.create("/zs", "zs".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println(path);
    }

    // 2.获取子节点并监控节点数据的变化
    @Test
    public void getDataAndWatch() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/", false);// 获取根目录下所有节

        for (String child : children) {
            System.out.println(child);
        }
        // 进程不终止
        Thread.sleep(Long.MAX_VALUE);
    }

    // 3.判断节点是否存在
    @Test
    public void exist() throws KeeperException, InterruptedException {

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

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

    }
}

加油!

感谢!

努力!

以上是关于Zookeeper实战API 应用的主要内容,如果未能解决你的问题,请参考以下文章

Dubbo实战 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务

Dubbo实战 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务

Dubbo实战 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务

Dubbo实战 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务(转)

打怪升级之小白的大数据之旅(五十五)<Zookeeper命令行与API应用>

大数据技术之Zookeeper