【ZooKeeper学习】1. 基础操作_connectedsemaphore.await();-程序员宅基地

技术标签: ZooKeeper  Zookeepr  Api  

1. ZooKeeper是什么
 
 
2. 基础操作
 
 
3. 原生Api支持
 
1、创建session
 
public class CreateSessionUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSessionUsage());
        //zookeeper 运行状态
        System.out.println(zooKeeper.getState());

        connectedSemaphore.await();

        System.out.println("ZooKeeper session established");
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event: " + event);
        if(Event.KeeperState.SyncConnected == event.getState()){
            connectedSemaphore.countDown();
        }
    }
}

 

 
2、创建复用session
public class CreateSessionWithSidUsage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSessionWithSidUsage());

        connectedSemaphore.await();

        long sessionId = zooKeeper.getSessionId();
        byte[] passwd = zooKeeper.getSessionPasswd();

        //错误session id 和 passwd
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSessionWithSidUsage(), 1l, "test".getBytes());

        //正确的session id 和 passwd
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSessionWithSidUsage(), sessionId, passwd);

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event: " + event);
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

 

3、创建节点
3.1同步创建临时节点和临时顺序节点
public class CreateSyncNodeUsage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000,new CreateSyncNodeUsage());
        connectedSemaphore.await();

        //同步创建临时节点
        String path1 = zooKeeper.create("/zk-test-node-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        System.out.println("Success create znode: "+ path1);

        //同步创建临时顺序节点
        String path2 = zooKeeper.create("/zk-test-node-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        System.out.println("Success create znode: "+ path2);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

 

 
3.2异步创建临时节点和临时顺序节点
public class CreateASyncNodeUsage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateASyncNodeUsage());

        connectedSemaphore.await();

        //异步临时节点
        zooKeeper.create("/zk-test-node-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new IStringCallback(), "I am context");
        //异步临时节点 此时已创建过 返回-110错误
        zooKeeper.create("/zk-test-node-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new IStringCallback(), "I am context");
        //异步创建临时顺序节点
        zooKeeper.create("/zk-test-node-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new IStringCallback(), "I am context");

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

class IStringCallback implements AsyncCallback.StringCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
        System.out.println("Create path result: [" + rc + "," + path + "," + ctx + ",real path name: " + name);
    }
}

 

 
4、删除节点
public void delete(String path, int version)
public void delete(String path, int version, VoidCallback cb, Object ctx)

 

 
5、读取数据
5.1同步获取子节点
public class GetChildrenUsage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;


    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new GetChildrenUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.create(path + "/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        List<String> childrenList = zooKeeper.getChildren(path, true);

        System.out.println(childrenList);

        zooKeeper.create(path + "/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        Thread.sleep(Integer.MAX_VALUE);

    }

    @Override
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                connectedSemaphore.countDown();
            }else if(event.getType() == Event.EventType.NodeChildrenChanged){
                try {
                    System.out.println("ReGet Child:"+zooKeeper.getChildren(event.getPath(),true));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 
5.2异步获取子节点
public class AsynGetChildrenUsage implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;


    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new AsynGetChildrenUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.create(path + "/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        zooKeeper.getChildren(path, true,new IChildren2Callback(),null);

        zooKeeper.create(path + "/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        Thread.sleep(Integer.MAX_VALUE);

    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeChildrenChanged) {
                try {
                    System.out.println("ReGet Child:" + zooKeeper.getChildren(event.getPath(), true));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class IChildren2Callback implements AsyncCallback.Children2Callback {

    @Override
    public void processResult(int rc, String path, Object ctx, List<String> list, Stat stat) {
        System.out.println("Create path result: [" + rc + "," + path + "," + ctx + ",children list: " + list + "stat " + stat);
    }
}

 

 
5.3同步获取数据
public class GetDataUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new GetDataUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        System.out.println(new String(zooKeeper.getData(path, true, stat)));

        System.out.println(stat.getCzxid() + "," + stat.getMzxid() + "," + stat.getVersion());

        zooKeeper.setData(path, "123".getBytes(), -1);

        Thread.sleep(Integer.MAX_VALUE);

    }


    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    System.out.println(new String(zooKeeper.getData(event.getPath(), true, stat)));
                    System.out.println(stat.getCzxid() + "," + stat.getMzxid() + "," + stat.getVersion());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 
5.4异步获取数据
public class AsynGetDataUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new AsynGetDataUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        zooKeeper.getData(path, true, new IDataCallback(), null);


        zooKeeper.setData(path, "123".getBytes(), -1);

        Thread.sleep(Integer.MAX_VALUE);

    }


    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    zooKeeper.getData(event.getPath(), true, new IDataCallback(), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class IDataCallback implements AsyncCallback.DataCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println(rc + "," + path + "," + new String(data));

        System.out.println(stat.getCzxid() + "," + stat.getMzxid() + "," + stat.getVersion());
    }
}

 

 
6、更新数据
6.1同步更新数据
public class SetDataUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new SetDataUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        zooKeeper.getData(path,true,null);

        //zooKeeper中version 基于0开始 这里给-1就是一个标志 表示最新版本
        Stat stat = zooKeeper.setData(path, "456".getBytes(), -1);
        System.out.println(stat.getCzxid()+","+stat.getMzxid()+","+stat.getVersion());

        Stat stat2 = zooKeeper.setData(path, "456".getBytes(), stat.getVersion());
        System.out.println(stat2.getCzxid()+","+stat2.getMzxid()+","+stat2.getVersion());

        //此处更新失败 使用了失效的版本
        zooKeeper.setData(path,"456".getBytes(),stat.getVersion());

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                connectedSemaphore.countDown();
            }
        }
    }
}

 

 
6.2异步更新数据
public class AsynSetDataUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new AsynSetDataUsage());

        connectedSemaphore.await();

        zooKeeper.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);


        //此处更新失败 使用了失效的版本
        zooKeeper.setData(path,"456".getBytes(),-1,new IStatCallback(),null);

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                connectedSemaphore.countDown();
            }
        }
    }
}

class IStatCallback implements AsyncCallback.StatCallback{

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        if(rc == 0){
            System.out.println("SUCCESS");
        }
    }
}

 

 
7、检测节点是否存在
public class ExistNodeUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new ExistNodeUsage());

        connectedSemaphore.await();

        //true 为复用默认Watcher
        zooKeeper.exists(path, true);

        zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.setData(path, "123".getBytes(), -1);
        zooKeeper.create(path + "/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.delete(path + "/c1", -1);
        zooKeeper.delete(path, -1);

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        try {

            if (Event.KeeperState.SyncConnected == event.getState()) {
                if (Event.EventType.None == event.getType() && null == event.getPath()) {
                    connectedSemaphore.countDown();
                } else if (Event.EventType.NodeCreated == event.getType()) {
                    System.out.println("Node(" + event.getPath() + ")Created");
                    zooKeeper.exists(event.getPath(), true);
                } else if (Event.EventType.NodeDeleted == event.getType()) {
                    System.out.println("Node(" + event.getPath() + ")Deleted");
                    zooKeeper.exists(event.getPath(), true);
                } else if (Event.EventType.NodeDataChanged == event.getType()) {
                    System.out.println("Node(" + event.getPath() + ")DataChanged");
                    zooKeeper.exists(event.getPath(), true);
                }
            }
        } catch (Exception e) {
        }
    }
}

 

 
 
 
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/fengyu6623/article/details/104031155

智能推荐

html div背景自动居中显示,网站背景图居中自适应以及拉伸填充CSS代码解决方法...-程序员宅基地

文章浏览阅读915次。写这篇水文呢,也是最近在自己在魔改一个主题用作新做的班级网站。发现模版的背景图片以及其他地方的图片显示只能在电脑端看到,而在移动端不能够自适应。顺便也整理出来。首先是图片的居中自适应:需要先给CSS background-repeat 属性赋值no-repeat,使图片不重复只显示一张。然后再定位背景图像位置,给CSS background-position 属性赋值center,设置水平和垂直都..._div背景图片居中自适应

C++ 构造函数与析构函数,与成员初始化列表语法_const std::string&co-程序员宅基地

文章浏览阅读545次。理论知识:C++构造函数与析构函数关于函数有两个概念,函数的定义及函数的原型//函数的原型double sqrt(double);//函数的定义double sqrt(double x){ ..........}总结一句话:构造函数就是初始化,析构函数就是释放空间(以上的函数,均需要有函数的原型及定义)目录1关于构造函数(类的初始化)1.1explic..._const std::string&co

《高效程序员的45个习惯:敏捷开发修炼之道》读书笔记(二)_高效程序员的45个习惯(二)-程序员宅基地

文章浏览阅读290次。今天,终于看完了这本书,零零散散的时间加起来总共花了大约5h看完。好了,继续前面的读书笔记(一),来谈谈自己看了这本书之后的一些读书笔记。 从第五章到最后一章,在我之见,看完后体会最深的有以下几点: 其一,在用代码编程时,要遵循PIE原则(意图清楚而表达明确的编程,就叫PIE原则),也就是写代码要让团队其他人看后能看懂; 其二,代码不是写得越多越好,而是让它在看起来优雅与简单的基_高效程序员的45个习惯(二)

Java中几种创建并初始化List元素的方法(包含验证测试代码)-程序员宅基地

文章浏览阅读3.3k次。// 方法一: 常规方式 首先构造一个List,然后使用List.add进行初始化 List<String> list1 = new ArrayList<>(); list1.add("Java"); list1.add("C"); list1.add("C#"); log.info(">>>>>list1.size()>>>>>..._创建并初始化list

linux fio释放内存,Linux 中使用 Fio 测评硬盘性能-程序员宅基地

文章浏览阅读374次。Fio(Flexible I/O Tester) 是一款由 Jens Axboe 开发的用于测评和压力/硬件验证的自由开源的软件。它支持 19 种不同类型的 I/O 引擎 (sync、mmap、libaio、posixaio、SG v3、splice、null、network、 syslet、guasi、solarisaio,以及更多), I/O 优先级(针对较新的 Linux 内核),I/O 速..._ios=0/0, merge=0/0, ticks=0/0, in_queue=303462, util=0%

layui的简单使用_layui 设置div元素的class-程序员宅基地

文章浏览阅读832次。admin.html<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>STC电子流平台对接演示</title> <link rel="styl_layui 设置div元素的class

随便推点

PB实现微信、支付宝、新大陆星POS扫码支付接口_pb 微信扫码付接口文档-程序员宅基地

文章浏览阅读1.7k次。PB调用C#动态库实现新大陆星POS扫码支付接口。_pb 微信扫码付接口文档

黑马程序员-----java基础加强(一)_java怎么加强写好的方法-程序员宅基地

文章浏览阅读481次。---------------------- android培训、java培训、期待与您交流! 听张孝祥老师的课觉得他是一个为人和蔼,知识面丰富,不愧是软件行业的大哥! Eclipse的使用技巧1,MyEclipse 是Eclipse的插件,扩展了功能。 软件运行时:javaw进程运行 2.名词简写:Java EE (Java Platform,E_java怎么加强写好的方法

java代码控制layout_Margin参数_layout_marginstart代码中-程序员宅基地

文章浏览阅读1.5w次,点赞2次,收藏6次。声明本文属于个人所有,转载注明出处:http://blog.csdn.net/hnulwt/article/details/43671687问题描述今天在做android的界面,不过需要用java代码来动态生成一个界面,写起来不算难,但是在控制每行与上行的间隔的时候遇到了问题。在layout xml文件中,通过书写android:layout_marginLeft android:layout_ma_layout_marginstart代码中

Spring Boot 菜鸟教程 14 动态修改定时任务cron参数_springboot @cron动态传参-程序员宅基地

文章浏览阅读1.6w次。动态修改定时任务cron参数不需要重启应用就可以动态的改变Cron表达式的值不能使用@Scheduled(cron = "${jobs.cron}")实现_springboot @cron动态传参

IntelliJ IDEA配置Tomcat/Jetty运行Web项目-程序员宅基地

文章浏览阅读573次。一、使用Maven的POM引入插件的形式:这种方式只需在POM中引入Tomcat/Jetty的插件即可运行。参考:http://www.cnblogs.com/EasonJim/p/6687272.htmlPOM:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o..._idea配置jetty启动web项目

web.config与Global.asax_webconfig global-程序员宅基地

文章浏览阅读1k次。Web.config文件是一个XML文本文件,它用来储存ASP.NETWeb 应用程序的配置信息(如最常用的设置ASP.NETWeb 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中。当你通过.NET新建一个Web应用程序后,默认情况下会在根目录自动创建一个默认的Web.config文件,包括默认的配置设置,所有的子目录都继承它的配置设置。如果你想修改子目录的配置设置,你可以在该子目录_webconfig global