Zookeeper 原生api zkClient Curator操作

源码地址:

https://download.csdn.net/download/eussi/10697875

pom.xml依赖:

<dependency>
    <groupId>org.apache.zookeeper</groupId>
     <artifactId>zookeeper</artifactId>
     <version>3.4.8</version>
 </dependency>
 <dependency>
     <groupId>com.101tec</groupId>
     <artifactId>zkclient</artifactId>
     <version>0.10</version>
 </dependency>
 <!--客户端实现-->
 <dependency>
     <groupId>org.apache.curator</groupId>
     <artifactId>curator-framework</artifactId>
     <version>2.11.0</version>
 </dependency>
 <!--实现场景封装-->
 <dependency>
     <groupId>org.apache.curator</groupId>
     <artifactId>curator-recipes</artifactId>
     <version>2.11.0</version>
 </dependency>

这里主要列出curator代码:
CreateSessionDemo:

public class CreateSessionDemo {
    public final static String CONNECTIONSTRING =  "192.168.198.201:2181," +
            "192.168.198.202:2181," +
            "192.168.198.203:2181," +
            "192.168.198.204:2181";

    public static void main(String[] args) throws IOException, InterruptedException {
        //normal创建方式
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CONNECTIONSTRING, 5000, 5000,
                new ExponentialBackoffRetry(1000, 3)); //ExponentialBackoffRetry衰减重试

        curatorFramework.start();
        System.out.println("success:" + curatorFramework);

        //fluent风格
        CuratorFramework curatorFramework1 = CuratorFrameworkFactory.builder()
                .connectString(CONNECTIONSTRING)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
//                .namespace("/root")  //表示后续操作都是以此节点为根节点进行操作
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
        curatorFramework1.start();
        System.out.println("success:" + curatorFramework1);

    }
}

CuratorOperationDemo:

public class CuratorOperationDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        CuratorFramework curatorFramework = CuratorClientUtils.getInstance();

        String path = "/demo/demo1/demo2";
        try {
            //增
            String result = curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path, "123".getBytes());
            System.out.println("创建成功:" + result);

            //查
            Stat stat = new Stat();
            byte[] data = curatorFramework.getData()
                    .storingStatIn(stat)   //将节点状态信息存入stat中
                    .forPath(path);
            System.out.println("节点:" + path + ", \n内容:"
                    + new String(data)
                    + ", \nstat:"
                    + stat);

            //改
            stat = curatorFramework.setData().forPath(path, "456".getBytes());
            data = curatorFramework.getData()
                    .forPath(path);
            System.out.println("节点:" + path + ", \n修改后内容:"
                    + new String(data)
                    + ", \nstat:"
                    + stat);

            //删
            curatorFramework.delete().deletingChildrenIfNeeded()
                    .forPath(path.substring(0, path.indexOf("/", 2)));
            System.out.println("删除成功!");


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

        /**
         * 异步操作过程
         */
        System.out.println("-----------------------------------------------------------------------------------");
        path = "/async/async1";
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(5);
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .inBackground(new BackgroundCallback() {
                        @Override
                        public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                            System.out.println(Thread.currentThread().getName() + "-->"
                            + "\nresultCode:" + curatorEvent.getResultCode()
                            + "\nType:" + curatorEvent.getType()
                            + "\nPath:" + curatorEvent.getPath());
                            countDownLatch.countDown();
                        }
                    }, executorService)
                    .forPath(path, "123".getBytes());
            System.out.println("创建成功!");
            countDownLatch.await();
            executorService.shutdown();

            //删
            curatorFramework.delete().deletingChildrenIfNeeded()
                    .forPath(path.substring(0, path.indexOf("/", 2)));
            System.out.println("删除成功!");


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

        System.out.println("-----------------------------------------------------------------------------------");
        /**
         * 事务操作
         */

        try {
            Collection<CuratorTransactionResult> results = curatorFramework.inTransaction().create().forPath("/aaa") //报错,不存在,并且第一个也不会成功添加
                    .and().setData().forPath("/xxxx", "333".getBytes())
                    .and().commit();
            for(CuratorTransactionResult result: results) {
                System.out.println(result.getForPath() + "-->" + result.getType());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

CuratorEventDemo:

public class CuratorEventDemo {
    /**
     * 三种watcher来做时间监听:
     * PathCache 监视一个路径下子节点的创建,更新,删除
     * NodeCache 监视一个节点的创建,更新,删除
     * TreeCache 以上两个综合起来,监视路径下的创建,删除,更新,缓存路径下所有子节点的数据
     */



     public static void main(String[] args) throws IOException, InterruptedException {
        CuratorFramework curatorFramework = CuratorClientUtils.getInstance();

         try {
             String path = "/cache";
             final NodeCache nodeCache = new NodeCache(curatorFramework, path, false);
             nodeCache.start(true);

             nodeCache.getListenable().addListener(new NodeCacheListener() {
                 @Override
                 public void nodeChanged() throws Exception {
                     System.out.println("节点数据发生了变化");
                 }
             });

             curatorFramework.create().forPath(path, "123".getBytes());
             System.out.println("创建节点");

             curatorFramework.setData().forPath(path, "123456".getBytes());
             System.out.println("更新节点");

             curatorFramework.delete().forPath(path);
             System.out.println("删除节点");
             Thread.sleep(2000);

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

             PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, path, true);
             pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

             pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
                 @Override
                 public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                     switch (pathChildrenCacheEvent.getType()) {
                         case CHILD_ADDED:
                             System.out.println(pathChildrenCacheEvent.getType() + ":增加子节点");
                             break;
                         case CHILD_REMOVED:
                             System.out.println(pathChildrenCacheEvent.getType() + ":删除子节点");
                             break;
                         case CHILD_UPDATED:
                             System.out.println(pathChildrenCacheEvent.getType() + ":更新子节点");
                             break;
                         default:break;
                     }
                 }
             });

             curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath(path, "123".getBytes());
             System.out.println("创建节点");
             Thread.sleep(2000);      //触发太快会造成监听不到的情况

             curatorFramework.create().forPath(path + "/child", "123".getBytes());
             System.out.println("创建子节点");
             Thread.sleep(2000);

             curatorFramework.setData().forPath(path + "/child", "123456".getBytes());
             System.out.println("更新子节点");
             Thread.sleep(2000);

             curatorFramework.delete().forPath(path + "/child");
             System.out.println("删除子节点");
             Thread.sleep(2000);

             curatorFramework.delete().forPath(path);
             System.out.println("删除节点");

             Thread.sleep(5000);

             System.in.read();

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

     }
}

CuratorClientUtils:

public class CuratorClientUtils {
    public final static String CONNECTIONSTRING =  "192.168.198.201:2181," +
            "192.168.198.202:2181," +
            "192.168.198.203:2181," +
            "192.168.198.204:2181";
    public static CuratorFramework getInstance() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CONNECTIONSTRING, 5000, 5000,
                new ExponentialBackoffRetry(1000, 3)); //ExponentialBackoffRetry衰减重试

        curatorFramework.start();
        System.out.println("success:" + curatorFramework);
        return curatorFramework;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值