ZooKeeper API 開發


ZooKeeper API 開發

使用maven開發 ZooKeeper API

  1. 配置 pom.xml 文件
   <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. 開發實例
package codes.admin.bigdata.zk;

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;

import static java.lang.Long.MAX_VALUE;

public class ZkClient {

    private ZooKeeper zkCli;
    /**
     * 集羣節點
     */
    private static final String CONNECT_STRING = "hadoop141:2181,hadoop142:2181,hadoop143:2181";
    /**
     * 超時時間
     */
    private static final int SESSION_TIMEOUT = 2000;

    /**
     * 實例化zk
     *
     * zk監聽事件類型,監聽自己感興趣的事件,一旦事件觸發,這個時候會回調對應的函數
     * 監聽器只能用一次,如果需要監聽多次,需要重複監聽。
     *  public static enum EventType {
     *        None(-1),
     *        NodeCreated(1), //節點創建事件
     *        NodeDeleted(2),  //節點刪除事件
     *        NodeDataChanged(3),  //節點數據變化事件
     *        NodeChildrenChanged(4);  //節點子節點事件變化事件(子節點數量增加和減少)
     *  }
     *下面三個方法是可以綁定監聽器的:
     * zkCli.getChildren("/data",true);
     *      感興趣的事件:NodeChildrenChanged
     * zkCli.exists("/data",true);
     *      感興趣的事件:NodeCreated,NodeDeleted,NodeDataChanged
     * zkCli.getData("/data",true,null);
     *      感興趣的事件:NodeDataChanged
     * @throws IOException
     */
    @Before
    public void before() throws IOException {
        zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
            //當監聽器重複綁定監聽的時候 會重複調用 process() 方法
            @Override
            public void process(WatchedEvent watchedEvent) {
                //獲取事件類型
                System.out.println(watchedEvent.getType());
                //爲getChildren綁定監聽事件 true表示重複綁定 如果忘了重複綁定監聽,監聽器只會回調一次
                try {
                    zkCli.getChildren("/data",true);
                    //zkCli.exists("/data",true);
                    //zkCli.getData("/data",true,null);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    });
    }

    /**
     * 獲取子節點監聽節點變化
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void ls() throws KeeperException, InterruptedException {
        List<String> children = zkCli.getChildren("/", e->{
            System.out.println("自定義回調函數!");
        });

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

        Thread.sleep(MAX_VALUE);
    }

    /**
     * 創建子節點
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void create() throws InterruptedException, KeeperException {
        //OPEN_ACL_UNSAFE  能夠使所有用戶查看
        //EPHEMERAL 臨時創建
        //PERSISTENT 永久創建
        // PERSISTENT_SEQUENTIAL  永久創建 自動添加序號
        // EPHEMERAL_SEQUENTIAL   臨時創建 自動添加序號
        String idea = zkCli.create("/Idea", "Idea2020".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        //返回路徑
        System.out.println(idea);

        Thread.sleep(MAX_VALUE);
    }

    /**
     * 判斷Znode是否存在
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zkCli.exists("/Idea0000000006", false);

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

    /**
     * 獲取節點數據
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void get() throws KeeperException, InterruptedException {
        byte[] data = zkCli.getData("/1230000000004", false, new Stat());

        String dara = new String(data);

        System.out.println(dara);
    }

    /**
     * 設置節點數據
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void set() throws KeeperException, InterruptedException {
        Stat stat = zkCli.setData("/234", "hello world".getBytes(), 0);
        System.out.println(stat.getDataLength());
    }

    /**
     * 刪除節點
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void delete() throws KeeperException, InterruptedException {
        Stat exists = zkCli.exists("/234", false);
        if (exists != null){
            zkCli.delete("/234",exists.getVersion());
        }

    }

    /**
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void register() throws KeeperException, InterruptedException {
        byte[] data = zkCli.getData("/aa", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    register();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, null);

        System.out.println(new String(data));
    }

    @Test
    public void testRegister() throws KeeperException, InterruptedException {
        register();
        Thread.sleep(MAX_VALUE);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章