创建会话

  • 建立简单连接
/**
 * 测试创建Zk会话
 * Created by liuhuichao on 2017/7/25.
 */
public class ZooKeeper_Constructor_Usage_Simple implements Watcher {
    private static CountDownLatch connectedSemaphore=new CountDownLatch(1);

    public static void main(String[] args) throws Exception{
        ZooKeeper zk=new ZooKeeper("192.168.99.215:2181",5000,new ZooKeeper_Constructor_Usage_Simple());
        System.out.println(zk.getState());
        connectedSemaphore.await();
        System.out.println("zk session established");
    }

    /**
     * 处理来自ZK服务端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("receive watched event:"+watchedEvent);
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            connectedSemaphore.countDown();//解除等待阻塞
        }
    }
}
  • 复用会话
/**
 * 复用sessionId和sessionPassword的会话
 * Created by liuhuichao on 2017/7/25.
 */
public class ZooKeeper_Constructor_Usage_With_sid_password implements Watcher {

    private static CountDownLatch connectedSemaphore=new CountDownLatch(1);
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("receive watched event:"+watchedEvent);
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            connectedSemaphore.countDown();
        }

    }

    public static void main(String[] args) throws Exception{
        ZooKeeper zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password());
        connectedSemaphore.await();
        long sessionId=zooKeeper.getSessionId();
        byte[] password=zooKeeper.getSessionPasswd();

        /**使用错误的sessionID跟sessionPwd连连接测试[192.168.99.215 lhc-centos0]**/
        ZooKeeper zkWrong=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password(),1l,"lhc".getBytes());
        /**使用正确的来进行连接**/
        ZooKeeper zkTrue=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Constructor_Usage_With_sid_password(),sessionId,password);
        Thread.sleep(Integer.MAX_VALUE);
    }
}

创建节点

  • 使用同步API创建节点
/**
 * 使用同步API创建一个节点
 * Created by liuhuichao on 2017/7/25.
 */
public class ZooKeeper_Create_API_Sync_Usage implements Watcher {
    private static CountDownLatch connectedSemaphore=new CountDownLatch(1);
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            connectedSemaphore.countDown();
        }
    }

    public static void main(String[] args) throws Exception{
        ZooKeeper zooKeeper=new ZooKeeper("192.168.99.215:2181",5000,new ZooKeeper_Create_API_Sync_Usage());
        connectedSemaphore.await();
        String path1=zooKeeper.create("/zk-test1","lhc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);//临时结点
        System.out.println(path1+" 创建成功!");

        String path2=zooKeeper.create("/zk-test2","lllhhhhhhhhhhhhhhhhc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(path2+"  创建成功!");

    }
}
  • 使用异步API创建一个节点
/**
 * 使用异步API创建一个节点
 * Created by liuhuichao on 2017/7/25.
 */
public class ZooKeeper_Create_API_ASync_Usage implements Watcher{
    private static CountDownLatch connectedSamphore=new CountDownLatch(1);

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

    public static void main(String[] args) throws Exception{
        ZooKeeper zk1=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_Create_API_ASync_Usage());
        connectedSamphore.await();
        zk1.create("/zk-test-1","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,new IStringCallBack(),"i am a context");
        zk1.create("/zk-test-2","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,new IStringCallBack(),"i am a context");
        zk1.create("/zk-test-3","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL,new IStringCallBack(),"i am a context");
        Thread.sleep(Integer.MAX_VALUE);
    }
}

/**
 * Created by liuhuichao on 2017/7/26.
 */
public class IStringCallBack implements AsyncCallback.StringCallback{

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

删除节点

/**
 * 删除zk的持久结点
 * Created by liuhuichao on 2017/7/26.
 */
public class ZooKeeperDeleteNode implements Watcher {

    private  static CountDownLatch conntedSamphore=new CountDownLatch(1);
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            conntedSamphore.countDown();
        }

    }

    public static void main(String[] args) throws Exception{
        /**同步删除节点**/
        ZooKeeper zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeperDeleteNode());
        conntedSamphore.await();
        zooKeeper.delete("/zk-test-30000000014",0);
    }

}

读取数据

  • 使用同步API获取子节点列表
/**
 *获取结点-同步
 * Created by liuhuichao on 2017/7/26.
 */
public class ZooKeeper_GetChildren_API_Sync_Usage implements Watcher {
    private  static CountDownLatch conntedSamphore=new CountDownLatch(1);
    private static ZooKeeper zooKeeper=null;

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            conntedSamphore.countDown();
        }else if(watchedEvent.getType()== Event.EventType.NodeChildrenChanged){
            try {
                System.out.println("--------------------------------------reget children:"+zooKeeper.getChildren(watchedEvent.getPath(),true));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws Exception{
        String path="/zk-test-1";
        zooKeeper=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_GetChildren_API_Sync_Usage());
        conntedSamphore.await();
        zooKeeper.create(path+"/test1","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
        List<String> childrenList=zooKeeper.getChildren(path,true);
        System.out.println(childrenList);
        zooKeeper.create(path+"/test2","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
        Thread.sleep(Integer.MAX_VALUE);
    }

}

  • 使用异步API获取子节点列表
**
 * 异步获取结点
 * Created by liuhuichao on 2017/7/26.
 */
public class ZooKeeper_GetChildren_API_ASync_Usage implements Watcher {

    private static CountDownLatch connectedSemphore=new CountDownLatch(1);
    private static ZooKeeper zk=null;

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            connectedSemphore.countDown();
        }else if(watchedEvent.getType()== Event.EventType.NodeChildrenChanged){
            try {
                System.out.println("node changed===="+zk.getChildren(watchedEvent.getPath(),true));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws Exception{
        String path="/zk-test-1";
        zk=new ZooKeeper("lhc-centos0:2181",5000,new ZooKeeper_GetChildren_API_ASync_Usage());
        connectedSemphore.await();
        zk.create(path+"/test3","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.getChildren(path,true,new ICChild2Callback(),null);
        Thread.sleep(Integer.MAX_VALUE);
    }

}

/**
 * 异步获取结点回调接口
 * Created by liuhuichao on 2017/7/26.
 */
public class ICChild2Callback implements AsyncCallback.Children2Callback{

    @Override
    public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
        System.out.println("get children zonde result:[reponse code:"+rc+" path="+path+" ctx="+ctx+"  childrenlist="+children+" stat="+stat);
    }
}
  • 使用同步API获取结点数据
/**
 *
 * 同步获取数据
 * Created by liuhuichao on 2017/7/27.
 */
public class GetData_API_Sync_Usage  implements Watcher{

    private static CountDownLatch conntedSamphore=new CountDownLatch(1);
    private static ZooKeeper zk=null;
    private static Stat stat=new Stat();
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            conntedSamphore.countDown();
        }else if(watchedEvent.getType()== Event.EventType.NodeCreated){
            System.out.println("node changed:"+watchedEvent.getPath());
        }

    }

    public static void main(String[] args) throws Exception{
        String path="/test-1";
       zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());
        conntedSamphore.await();
        System.out.println("zk-19 连接成功!");
        //zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());
        System.out.println("children node:"+children);
        zk.setData(path+"/lhc","memeda".getBytes(),-1);
        byte[] nodeValue=zk.getData(path+"/lhc",true,stat);
        System.out.println(new String(nodeValue));

    }
}
  • 使用异步API获取结点数据
/**
 *
 * 同步/异步获取数据
 * Created by liuhuichao on 2017/7/27.
 */
public class GetData_API_Sync_Usage  implements Watcher{

    private static CountDownLatch conntedSamphore=new CountDownLatch(1);
    private static ZooKeeper zk=null;
    private static Stat stat=new Stat();
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            conntedSamphore.countDown();
        }else if(watchedEvent.getType()== Event.EventType.NodeCreated){
            System.out.println("node changed:"+watchedEvent.getPath());
        }

    }

    public static void main(String[] args) throws Exception{
        String path="/test-1";
       zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());
        conntedSamphore.await();
        System.out.println("zk-19 连接成功!");
        //zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());
        System.out.println("children node:"+children);
        zk.setData(path+"/lhc","lllhc".getBytes(),-1);
        zk.getData(path+"/lhc",true,new IDataCallback(),null);//异步获取数据
        Thread.sleep(Integer.MAX_VALUE);
    }
}

/**
 * 异步获取node数据回调
 * Created by liuhuichao on 2017/7/27.
 */
public class IDataCallback implements AsyncCallback.DataCallback {
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("rc="+rc+" ;path="+path+" ;ctx="+ctx+" ;data="+data+" ;stat="+stat);
        System.out.println("string data="+new String(data));
        System.out.println("max version="+stat.getVersion());
    }
}

更新数据

  • 同步设置数据
  zk.setData(path+"/lhc","lllhc".getBytes(),-1);//同步设置数据
  • 异步设置数据
/**
 *
 * 同步/异步获取数据
 * Created by liuhuichao on 2017/7/27.
 */
public class GetData_API_Sync_Usage  implements Watcher{

    private static CountDownLatch conntedSamphore=new CountDownLatch(1);
    private static ZooKeeper zk=null;
    private static Stat stat=new Stat();
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            conntedSamphore.countDown();
        }else if(watchedEvent.getType()== Event.EventType.NodeCreated){
            System.out.println("node changed:"+watchedEvent.getPath());
        }

    }

    public static void main(String[] args) throws Exception{
        String path="/test-1";
       zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new GetData_API_Sync_Usage());
        conntedSamphore.await();
        System.out.println("zk-19 连接成功!");
        //zk.create(path+"/lhc", "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        List<String> children=zk.getChildren(path,new GetData_API_Sync_Usage());
        System.out.println("children node:"+children);
        //zk.setData(path+"/lhc","lllhc".getBytes(),-1);//同步设置数据
        zk.setData(path+"/lhc","lhc".getBytes(),-1,new IStatCallback(),null);
        zk.getData(path+"/lhc",true,new IDataCallback(),null);//异步获取数据
        Thread.sleep(Integer.MAX_VALUE);
    }
}

/**
 * 异步设置数据回调接口
 * Created by liuhuichao on 2017/7/27.
 */
public class IStatCallback implements AsyncCallback.StatCallback{
    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println("rc="+rc+" ;path="+path+" ;ctx="+ctx+" ;stat="+stat);
        if(rc==0){
            System.out.println("数据设置成功!");
        }
    }
}

检测节点是否存在


/**
 * 检测zk node
 * Created by liuhuichao on 2017/7/27.
 */
public class Exist_API_Sync_Usage implements Watcher{
    private static CountDownLatch connetedSamphore=new CountDownLatch(1);
    private static ZooKeeper zk=null;

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
            connetedSamphore.countDown();
        }else if(Event.EventType.NodeCreated==watchedEvent.getType()){
            System.out.println("node created=="+watchedEvent.getPath());
        }else if(Event.EventType.NodeDataChanged==watchedEvent.getType()){
            System.out.println("node changed=="+watchedEvent.getPath());
        }else if(Event.EventType.NodeDeleted==watchedEvent.getType()){
            System.out.println("node deleted=="+watchedEvent.getPath());
        }
    }

    public static void main(String[] args)throws Exception {
        String path="/test-1";
        zk =new ZooKeeper("rc-zkp-datn-rse-nmg-ooz-woasis:2181",5000,new Exist_API_Sync_Usage());
        connetedSamphore.await();
        System.out.println("zk-19 连接成功!");
        Stat stat=zk.exists(path,new Exist_API_Sync_Usage());
        System.out.println("stat="+stat==null?"为空":"不为空");
        zk.setData(path,"".getBytes(),-1);
        Thread.sleep(Integer.MAX_VALUE);

    }
}

Java API操作ZK node的更多相关文章

  1. MongoDB Java API操作很全的整理

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,一般生产上建议以共享分片的形式来部署. 但是MongoDB官方也提供了其它语言的客户端操作API.如下图所示: 提供了C.C++ ...

  2. hive-通过Java API操作

    通过Java API操作hive,算是测试hive第三种对外接口 测试hive 服务启动 package org.admln.hive; import java.sql.SQLException; i ...

  3. hadoop2-HBase的Java API操作

    Hbase提供了丰富的Java API,以及线程池操作,下面我用线程池来展示一下使用Java API操作Hbase. 项目结构如下: 我使用的Hbase的版本是 hbase-0.98.9-hadoop ...

  4. 使用Java API操作HDFS文件系统

    使用Junit封装HFDS import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org ...

  5. Kafka系列三 java API操作

    使用java API操作kafka 1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs ...

  6. Hadoop之HDFS(三)HDFS的JAVA API操作

    HDFS的JAVA API操作 HDFS 在生产应用中主要是客户端的开发,其核心步骤是从 HDFS 提供的 api中构造一个 HDFS 的访问客户端对象,然后通过该客户端对象操作(增删改查)HDFS ...

  7. zookeeper的java api操作

    zookeeper的java api操作 创建会话: Zookeeper(String connectString,int sessionTimeout,Watcher watcher) Zookee ...

  8. java api操作

    java api操作 导入开发包 将hbase安装包中lib下包导入java项目   创建表   Configuration conf = HBaseConfiguration.create(); c ...

  9. HDFS 05 - HDFS 常用的 Java API 操作

    目录 0 - 配置 Hadoop 环境(Windows系统) 1 - 导入 Maven 依赖 2 - 常用类介绍 3 - 常见 API 操作 3.1 获取文件系统(重要) 3.2 创建目录.写入文件 ...

随机推荐

  1. 20145216史婧瑶《Java程序设计》第9周学习总结

    20145216 <Java程序设计>第9周学习总结 教材学习内容总结 第十六章 整合数据库 16.1 JDBC入门 撰写应用程序是利用通信协议对数据库进行指令交换,以进行数据的增删查找. ...

  2. Qt大小端

    转:http://blog.csdn.net/usownh/article/details/42614185 大端模式和小端模式是计算机中经常涉及到的两种字节序,也有大端对齐.小端对齐.大尾.小尾等叫 ...

  3. 可扩展多线程异步Socket服务器框架EMTASS 2.0 (转自:http://blog.csdn.net/hulihui)

    可扩展多线程异步Socket服务器框架EMTASS 2.0 (转自:http://blog.csdn.net/hulihui) 0 前言 >>[前言].[第1节].[第2节].[第3节]. ...

  4. 搭建springmvc

    对于SpringMvc来说,搭建这框架,首先引入相应的包.如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xml ...

  5. mysql5.7.22安装步骤

    在官网上下载mysql的压缩包,然后解压 (下载地址:https://dev.mysql.com/downloads/mysql/) 1.打开cmd,建议使用管理员的身份打开cmd,如果不用使用管理员 ...

  6. 【bzoj2734】集合选数(有点思维的状压dp)

    题目传送门:bzoj2734 这题一个月前看的时候没什么头绪.现在一看,其实超简单. 我们对于每个在$ [1,n] $范围内的,没有因数2和3的数$ d $,将它的倍数$ 2^a 3^b d $一起处 ...

  7. mybatis的一级缓存和二级缓存(1)

    1.mybatis一级缓存,sqlSesion级别的缓存,一级缓存默认一直开启的,sqlSession级别的一个Map,把查询的数据放到一个Map中,以后需要相同的数据,直接从Map中去取 与数据库一 ...

  8. MS SQL2008执行大脚本文件时,提示“内存不足”的解决办法

    问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是当数据库导出脚本很大,用Microsoft SQL Server Management Studio执行 ...

  9. 键盘对应数字-keycode值大全(转)

    event.keycode值大全   keycode 8 = BackSpace BackSpace    keycode 9 = Tab Tab    keycode 12 = Clear    k ...

  10. Mac下新安装的MySQL无法登陆root用户解决方法

      一 设置MySQL命令行搜索路径 0.苹果->系统偏好设置->最下边点mysql 在弹出页面中 启动mysql服务 1.打开终端,输入: sudo vi ~/.bash_profile ...