基于curator framework zk工具使用

1 篇文章 0 订阅
1 篇文章 0 订阅

基于curator framework zk工具使用

1.添加依赖

 		<dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>

自己封装工具类

package com.wang.zookeeper.util;

import com.google.common.base.Stopwatch;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * zookeeper工具类
 */
public class ZKClient {
    /**
     * 客户端
     */
    private CuratorFramework client = null;

    /**
     * 构造方法
     *
     * @param connectionInfo zk主机
     */
    public ZKClient(String connectionInfo) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        client = CuratorFrameworkFactory.newClient(connectionInfo, retryPolicy);

        client.start();
    }

    /**
     * 创建节点
     *
     * @param path       路径
     * @param createMode 节点类型
     * @param data       节点数据
     * @return 是否创建成功
     */
    public boolean crateNode(String path, CreateMode createMode, String data) {
        try {
            client.create().withMode(createMode).forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 删除节点
     *
     * @param path 路径
     * @return 删除结果
     */
    public boolean deleteNode(String path) {
        try {
            client.delete().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 删除一个节点,并且递归删除其所有的子节点
     *
     * @param path 路径
     * @return 删除结果
     */
    public boolean deleteChildrenIfNeededNode(String path) {
        try {
            client.delete().deletingChildrenIfNeeded().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 判断节点是否存在
     *
     * @param path 路径
     * @return true-存在  false-不存在
     */
    public boolean isExistNode(String path) {
        try {
            Stat stat = client.checkExists().forPath(path);

            return stat != null ? true : false;
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }
    }

    /**
     * 判断节点是否是持久化节点
     *
     * @param path 路径
     * @return 2-节点不存在  | 1-是持久化 | 0-临时节点
     */
    public int isPersistentNode(String path) {
        try {
            Stat stat = client.checkExists().forPath(path);

            if (stat == null) {
                return 2;
            }

            if (stat.getEphemeralOwner() > 0) {
                return 1;
            }

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

            return 2;
        }
    }

    /**
     * 获取节点数据
     *
     * @param path 路径
     * @return 节点数据,如果出现异常,返回null
     */
    public String getNodeData(String path) {

        try {
            byte[] bytes = client.getData().forPath(path);
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 注册节点数据变化事件
     *
     * @param path              节点路径
     * @param nodeCacheListener 监听事件
     * @return 注册结果
     */
    public boolean registerWatcherNodeChanged(String path, NodeCacheListener nodeCacheListener) {
        NodeCache nodeCache = new NodeCache(client, path, false);
        try {
            nodeCache.getListenable().addListener(nodeCacheListener);

            nodeCache.start(true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 注册节点数据变化事件
     *
     * @param path              节点路径
     * @param treeCacheListener 监听事件
     * @return 注册结果
     */
    public boolean registerWatcherAllNodeChanged(String path, TreeCacheListener treeCacheListener) {
        TreeCache treeCache = new TreeCache(client, path);
        try {
            treeCache.start();
            treeCache.getListenable().addListener(treeCacheListener);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 更新节点数据
     *
     * @param path     路径
     * @param newValue 新的值
     * @return 更新结果
     */
    public boolean updateNodeData(String path, String newValue) {
        //判断节点是否存在
        if (!isExistNode(path)) {
            return false;
        }

        try {
            client.setData().forPath(path, newValue.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 开启事务
     *
     * @return 返回当前事务
     */
    public CuratorTransaction startTransaction() {
        return client.inTransaction();
    }

}

main方法测试

节点增删改查,并且监听节点下所有事件

    public static void main(String[] args) throws InterruptedException {
        String url = "127.0.0.1:2181";
        Stopwatch stopwatch = Stopwatch.createStarted();
        ZKClient zkClient = new ZKClient(url);
        stopwatch.stop();
        System.out.println("zk连接成功,耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "毫秒");

        boolean root = zkClient.isExistNode("/");
        System.out.println("节点/是否存在:" + root);

        boolean existNode = zkClient.isExistNode("/dubbo");
        System.out.println("节点/dubbo是否存在:" + existNode);

        if (existNode) {
//            boolean delNode = zkClient.deleteChildrenIfNeededNode("/dubbo");
//            System.out.println("节点/dubbo是否删除成功:" + delNode);

        } else {
            boolean crateNode = zkClient.crateNode("/dubbo", CreateMode.PERSISTENT, "我是天地");
            System.out.println("节点/dubbo是否创建成功:" + crateNode);
        }

        zkClient.registerWatcherAllNodeChanged("/dubbo", (curatorFramework, treeCacheEvent) -> {
            System.out.println("=======节点:" + treeCacheEvent.getType() + "发生变化=======");
            ChildData childData = treeCacheEvent.getData();
            switch (treeCacheEvent.getType()) {
                case NODE_ADDED:
                    System.out.println("/dubbo节点,新增节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
                    break;
                case NODE_REMOVED:
                    System.out.println("/dubbo节点,删除节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
                    break;
                case NODE_UPDATED:
                    System.out.println("/dubbo节点,修改节点:" + childData.getPath() + ",节点内容:" + new String(childData.getData()));
                    break;
                default:
                    System.out.println("当前事件:" + treeCacheEvent.getType() + ",非节点变动事件,不做处理");
                    break;
            }
        });

        String data = zkClient.getNodeData("/dubbo");
        System.out.println("节点/dubbo获取内容:" + data);


        boolean existCbdNode = zkClient.isExistNode("/dubbo/cbd");
        System.out.println("节点/dubbo/cbd是否存在:" + existCbdNode);
        if (!existCbdNode) {
            boolean crateCbdNode = zkClient.crateNode("/dubbo/cbd", CreateMode.PERSISTENT, "我是cbd");
            System.out.println("节点/dubbo是否创建成功:" + crateCbdNode);
        }

        String cbdata = zkClient.getNodeData("/dubbo/cbd");
        System.out.println("节点/dubbo/cbd获取内容:" + cbdata);

        new CountDownLatch(1).await();
    }

上面监听状态下。另外服务更新节点

public static void main(String[] args) {
        String url = "127.0.0.1:2181";
        Stopwatch stopwatch = Stopwatch.createStarted();
        ZKClient zkClient = new ZKClient(url);
        stopwatch.stop();
        System.out.println("zk连接成功,耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "毫秒");


        String path = "/dubbo/sss";

        boolean existCbdNode = zkClient.isExistNode(path);
        System.out.println("节点/dubbo/sss是否存在:" + existCbdNode);
        if (!existCbdNode) {
            boolean crateCbdNode = zkClient.crateNode(path, CreateMode.PERSISTENT, "我是sss");
            System.out.println("节点/dubbo/sss是否创建成功:" + crateCbdNode);
        } else {

            boolean updateCbdNode = zkClient.updateNodeData(path, "我是变更后的sss");
            System.out.println("节点/dubbo/sss是否更新成功:" + updateCbdNode);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            zkClient.deleteNode(path);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值