ZooKeeper使用入門

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\test\java\目錄創建com\aotian\curator\test\Tester.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

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

台北網頁設計公司這麼多該如何選擇?

※智慧手機時代的來臨,RWD網頁設計為架站首選

※評比南投搬家公司費用收費行情懶人包大公開

※回頭車貨運收費標準

聚甘新