ZooKeeper使用入门

ZooKeeper简介

ZooKeeper是一个分布式的,开源的分布式应用程序协调服务,是Hadoop的子项目之一。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。

安装ZooKeeper

操作系统要求

操作系统 客户端 服务端 原生客户端 附加组件
GNU/Linux 开发/生产 开发/生产 开发/生产 开发/生产
Solaris 开发/生产 开发/生产 不支持 不支持
FreeBSD 开发/生产 开发/生产 不支持 不支持
Windows 开发/生产 开发/生产 不支持 不支持
Mac OS X 开发 开发 不支持 不支持

软件要求

Java 8及Java 11以上版本(Java 9和10不支持)

硬件要求

此硬件资源为官网推荐的配置,实际开发过程中不需要这么大,笔者测试1核1G内存20G硬盘的虚拟机即可运行。

  • 2核
  • 2G内存
  • 80G硬盘

下载安装并进行单点配置

  1. 下载页面地址:https://zookeeper.apache.org/releases.html
  2. 官网只提供tar.gz格式的压缩包,windows下载后按照zip之类的解压方式可能会导致解压后的包无法使用,笔者使用Git带的命令行执行linux的解压命令解压后使用,如果没有安装Git则建议使用虚拟机安装Linux使用。以下是正确解压和错误解压后的对比。

正确打开方式

错误打开方式

  1. 解压后的ZooKeeper默认是无法执行的,需要进行配置,将 apache-zookeeper-3.6.1/conf/zoo_sample.cfg复制一份并重命名为zoo.cfg,没什么特殊需要里边的配置项默认即可,笔者因为是在windows下使用,所以将datadir修改了。配置文件项说明如下:
配置项 说明
tickTime ZooKeeper使用的时间,单位毫秒,一般用于心跳检测,而ZooKeeper中的最小session超时时间是此项的两倍
dataDir 保留内存数据库快照的地址,如果不单独指定,事务日志也会记录在此
clientPort 服务端监听的端口号
initLimit 集群中的follower服务器与leader服务器之间初始连接时的最大心跳数
syncLimit 集群中follower服务器与leader服务器之间通讯时的最大心跳数
  1. 配置完成后即可在bin目录下执行对应的文件启动了,Windows下为zkServer.bat,Linux下为zkServer.sh

ZooKeeper应用

通过zkCli进行使用

  1. ZooKeeper启动后,可以通过bin目录下自带的客户端进行访问,Windows下为zkCli.bat,Linux下为zkCli.sh
  2. 启动时默认连接localhost:2181,如果有需要连接远程或其他端口的情况,可以如下添加参数:
zkCli.sh -server IP:Port
  1. 进入客户端后执行help(此处是一个随意的指令,只要不是zkCli支持的操作都可以)可查看其支持的操作,关于所有操作的介绍请参考官方页面:https://zookeeper.apache.org/doc/current/zookeeperCLI.html

  2. 常用操作介绍:

  • 查看节点信息,节点路径不能以“/”结尾
ls /
ls /zookeeper
  • 创建一个节点
create /test
create /test/testa
  • 查看节点状态
stat /test
stat /test/testa
  • 删除节点
# 删除单个空节点
delete /test/testa
delete /test

# 级联删除
deleteall /test

*退出客户端

quit

通过ZooKeeper客户端使用

因为笔者的第一开发语言是Java,这里以Java为例。常用的ZooKeeper Java客户端用zkclient和Apache Curator两种。zkclient是github上的一个开源项目,该项目在2018年10月2日后停止更新;Apache Curator是Apache基金会的开源项目,目前持续更新,推荐使用。常用的分布式RPC框架DUBBO也在2019年1月份推出的2.7.0版本中将默认的ZooKeeper客户端由zkclient切换为Apache Curator,此文中的示例也使用Apache Curator。

  1. 创建一个Maven项目,然后在pom.xml中引用Apache Curator,以下是笔者的文件内容,除了Apache Curator外添加了测试使用的junit并设置了编译使用的java版本。
<?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>org.example</groupId>
    <artifactId>apache-curator</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  1. 之后在src estjava目录创建comaotiancurator estTester.java,文件基本框架如下,主要是创建一个空的测试类
public class Tester {

    @Test
    public void testCurator() {
      
    }

}
  1. 接下来就是使用Apache Curator提供的API对ZooKeeper进行访问了。首先介绍下常用的API
  • 创建客户端
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
curatorFramework.start();
  • 检查节点是否存在,存在的话返回Stat对象,不存在则返回null
curatorFramework.checkExists().forPath("/localhost/aotian");
  • 创建节点,forPath第二个参数可以指定节点内容,不设置时创建空节点
curatorFramework.create().creatingParentContainersIfNeeded().forPath("/localhost/aotian", message.getBytes());
  • 设置节点内容,仅适用于已存在的节点,否则会报错
curatorFramework.setData().forPath("/localhost/aotian", message.getBytes());
  • 获取节点信息,以下代码表示将获取的节点信息保存到result对象。
Stat result = new Stat();
curatorFramework.getData().storingStatIn(result).forPath("/localhost/aotian");
  • 获取节点内容
byte[] results = curatorFramework.getData().forPath("/localhost/aotian");
  1. 完整示例如下,结尾添加了线程睡眠的代码,可以在睡眠时间内通过zkCli查看服务端中的内容。
    @Test
    public void testCurator() {
        // 创建客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
        curatorFramework.start();
        // 定义节点内容
        String message = "testCurator";
        try {
            // 判断节点是否存在不存在则创建,存在则设置指定值
            Stat a = curatorFramework.checkExists().forPath("/localhost/aotian");
            if (a == null){
                curatorFramework.create()
                        .creatingParentContainersIfNeeded()
                        .forPath("/localhost/aotian", message.getBytes());
            }else{
                curatorFramework.setData().forPath("/localhost/aotian", message.getBytes());
            }

            // 获取节点信息
            Stat result = new Stat();
            curatorFramework.getData().storingStatIn(result).forPath("/localhost/aotian");
            System.out.println(result.getCtime());

            // 获取节点内容
            byte[] results = curatorFramework.getData().forPath("/localhost/aoitan");
            System.out.println(new String(results));

            // 线程睡10S,这段时间内可以通过客户端查看节点内的信息,结束后只能查看到空节点
            Thread.sleep(100000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            curatorFramework.close();
        }
    }

ZooKeeper集群搭建

ZooKeeper集群中包含两种角色:Leader和Follower,因为ZooKeeper集群是半数节以上节点正常时才会正常提供服务,所以一般ZooKeeper集群中节点数量均为奇数。我们按照最小数量算,准备三台zookeeper服务器。

  1. 分别按照本文一开始的单机配置配置好三个ZooKeeper服务。个人联系或可以在同一台机器上部署三个ZooKeeper,只要解决端口冲突问题即可,实际生产过程中务必使用三台机器进行搭建,否则一旦机器出问题则整个集群瘫痪。
  2. 准备好三台ZooKeeper服务器之后我们准备开始集群的配置,首先我们需要规划好ZooKeeper的ID,然后在datadir属性对应的目录下创建一个myid文件。然后在文件内写上当前服务对应的ID,笔者规划的是0、1、2,所以我需要添加的配置文件如下:
IP地址 文件路径 文件内容
192.168.142.7 /tmp/zookeeper/myid 0
192.168.142.8 /tmp/zookeeper/myid 1
192.168.142.9 /tmp/zookeeper/myid 2

datadir属性默认在/tmp目录下,此目录会被定期清理掉,生产环境不要使用。

3、配置完以上文件后,需要配置之前的zoo.cfg,在最后添加以下内容,其中server.*对应myid文件中的ID号,192.168.142.7是IP地址,2888是ZooKeeper集群的通讯端口,3888是集群选取Leader使用的端口。

server.0=192.168.142.7:2888:3888
server.1=192.168.142.8:2888:3888
server.2=192.168.142.9:2888:3888

4、最后检查防火墙是否开放了2181、2888、3888端口,确认开放后启动ZooKeeper即可。通过执行zkServer.sh status命令可以查看当前机器的状态。

[root@centos-server-01 bin]# ./zkServer.sh status
/usr/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/apache-zookeeper-3.6.0/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower

[root@centos-server-02 bin]# ./zkServer.sh status
/usr/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/apache-zookeeper-3.6.0/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: leader
原文地址:https://www.cnblogs.com/aotian/p/13155203.html