zookeeper原生API操作

版权声明:尊重原创 https://blog.csdn.net/qq_41256709/article/details/88117089
/**
 * Zookeeper 学习
 * watcher(事件监听器)
 * @author Kevin
 */
public class ZookeeperBase {

    /**
     *  zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.73.128:2181,192.168.73.131:2181,192.168.73.132:2181";
    /**
     * session超时时间,毫秒
     */
    static final int SESSION_OUTTIME = 2000;
    /**
     * 信号量,阻塞程序执行,用于等待zookeeper连接成功,发送成功信号
     */
    static final CountDownLatch connectedSemaphore = new CountDownLatch(1);
    /**
     * zk变量
     */
    static ZooKeeper zk = null;

    public static void main(String[] args) throws Exception {
        zk = new ZooKeeper(CONNECT_ADDR, SESSION_OUTTIME, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                //获取事件的状态
                KeeperState keeperState = event.getState();
                EventType eventType = event.getType();
                //如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    //第一次建立连接时,事件状态为null
                    if (EventType.None == eventType) {
                        System.out.println("zk 建立连接");
                        //如果建立连接成功,则发送信号量,让后续阻塞程序向下执行
                        connectedSemaphore.countDown();
                    }
                }
            }
        });

        //进行阻塞
        connectedSemaphore.await();

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

        String path = "/testRoot";
        String data = "测试数据";
        //判断一个节点是否已经存在
        Stat stat = nodeExists(path, true);
        if (stat == null) {//该节点不存在,创建一个
            createNode(path, data, true);
        }
        //获取该节点的内容
        System.out.println(readData(path,false));
        //更新该节点的数据
        updateData(path,"更新后的数据");
        //获取该节点更新后的内容
        System.out.println(readData(path,false));
        //获取该节点下的所有子节点
        List<String> childrenList = getChildren(path,false);
        for(String children:childrenList){
            System.out.println(children);
        }
        //删除节点
        deleteNode(path);
        //关闭连接
        zk.close();
    }

    /**
     * 判断指定的节点是否已经存在
     *
     * @param path
     * @param needWatch
     * @return
     */
    public static Stat nodeExists(String path, boolean needWatch) {
        try {
            return zk.exists(path, needWatch);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建节点
     * @param path
     * @param data
     * @param watcher
     * @return
     */
    public static boolean createNode(String path, String data, boolean watcher) {
        try {
            //判断节点是否已存在
            zk.exists(path, watcher);
            System.out.println("节点创建成功,path:" + zk.create(
                    //路径
                    path,
                    //数据
                    data.getBytes(),
                    //所有可见
                    Ids.OPEN_ACL_UNSAFE,
                    //永久存储
                    CreateMode.PERSISTENT
            ) + ",content:" + data);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除指定节点
     * version -1 表示删除所有的版本
     * @param path
     */
    public static void deleteNode(String path) {
        try {
            zk.delete(path, -1);
            System.out.println("删除指定节点成功,path:" + path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新指定节点的内容
     * @param path
     * @param data
     * @return
     */
    public static boolean updateData(String path, String data) {
        try {
            System.out.println("更新数据成功,path" + path + ",stat" + zk.setData(path, data.getBytes(), -1));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取所有的子节点
     * @param path
     * @param needWatch
     * @return
     */
    public static List<String> getChildren(String path,boolean needWatch){
        try {
            return zk.getChildren(path, needWatch);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取指定节点数据内容
     * @param path
     * @param needWatch
     * @return
     */
    public static String readData(String path,boolean needWatch){
        try {
            return new String(zk.getData(path,needWatch,null));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41256709/article/details/88117089