Java简单操作Zookeeper

时间:2021-07-02 08:24:04

Zookeeper客户端链接

 

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.6</version>
</dependency>

 

package com.itman;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperHelloworld {

    /**
     * 集群地址
     */
    private static final String CONNECT_ADDRES = "169.254.197.135:2181";
    /**
     * 超时时间
     */
    private static final int SESSIONTIME = 2000;
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zk = new ZooKeeper(CONNECT_ADDRES, SESSIONTIME, new Watcher() {

            public void process(WatchedEvent event) {
                // 获取时间的状态
                KeeperState keeperState = event.getState();
                EventType tventType = event.getType();
                // 如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    if (EventType.None == tventType) {
                        // 如果建立连接成功,则发送信号量,让后阻塞程序向下执行
                        countDownLatch.countDown();
                        System.out.println("zk 建立连接");
                    }
                }
            }

        });
        // 进行阻塞
        countDownLatch.await();
        // 创建父节点
        // String result = zk.create("/testRott", "12245465".getBytes(),
        // Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // System.out.println("result:" + result);
        // 创建子节点
        String result = zk.create("/testRott/children", "children 12245465".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("result:" + result);
        zk.close();
    }

}

Watcher

package com.itman;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZkWatcher implements Watcher {

    /**
     * 集群地址
     */
    private static final String CONNECT_ADDRES = "169.254.197.135:2181";
    private static ZooKeeper zooKeeper;
    /**
     * 超时时间
     */
    private static final int SESSIONTIME = 2000;

    public ZkWatcher() {
        createConnection(CONNECT_ADDRES, SESSIONTIME);
    }

    // zk节点、发生变更、删除、修改 、 新增 事件通知
    public void process(WatchedEvent event) {
        KeeperState keeperState = event.getState();
        // 事件类型
        EventType eventType = event.getType();
        // 节点名称
        String path = event.getPath();
        System.out.println(
                "#####process()####调用####keeperState:" + keeperState + ",eventType:" + eventType + ",path:" + path);
        if (KeeperState.SyncConnected == keeperState) {
            // 连接类型
            if (EventType.None == eventType) {
                // 建立zk连接
                System.out.println("建立zk连接成功!");
            }
            // 创建类型
            if (EventType.NodeCreated == eventType) {
                System.out.println("####事件通知,当前创建一个新的节点####路径:" + path);
            }
            // 修改类型
            if (EventType.NodeDataChanged == eventType) {
                System.out.println("####事件通知,当前创建一个修改节点####路径:" + path);
            }
            // 删除类型
            if (EventType.NodeDeleted == eventType) {
                System.out.println("####事件通知,当前创建一个删除节点####路径:" + path);
            }
        }
        System.out.println("####################################################");
        System.out.println();
    }

    // 创建zk连接
    private void createConnection(String connectAddres, int sessiontime) {
        try {
            zooKeeper = new ZooKeeper(connectAddres, sessiontime, this);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    // 创建节点
    public void createNode(String path, String data) {
        try {
            String result = zooKeeper.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("创建节点成功....result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 修改节点
    public void updateNode(String path, String data) {
        try {
            zooKeeper.setData(path, data.getBytes(), -1);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    // 删除节点
    public void deleNode(String path) {
        try {
            zooKeeper.delete(path, -1);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public void close() {
        try {
            if (zooKeeper != null)
                zooKeeper.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static void main(String[] args) throws KeeperException, InterruptedException {
        ZkWatcher zkWatcher = new ZkWatcher();
        // zkWatcher.createNode("/parent1", "6452852");
        String path = "/parent1";
        zooKeeper.exists(path, true);
        // zkWatcher.updateNode(path, "88888");
        zkWatcher.deleNode(path);
        zkWatcher.close();
    }
}