Java API操作ZK node

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 创建会话建立简单连接/** * 测试创建Zk会话 * Created by liuhuichao on 2017/7/25. */public class ZooKeeper_Constructor_Usage_Simple implements Watche...

创建会话

  • 建立简单连接
/**
 * 测试创建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);

    }
}
相关实践学习
基于MSE实现微服务的全链路灰度
通过本场景的实验操作,您将了解并实现在线业务的微服务全链路灰度能力。
目录
相关文章
|
8天前
|
分布式计算 DataWorks Java
DataWorks操作报错合集之在使用MaxCompute的Java SDK创建函数时,出现找不到文件资源的情况,是BUG吗
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
24 0
|
8天前
|
Java 测试技术 Python
《手把手教你》系列技巧篇(三十六)-java+ selenium自动化测试-单选和多选按钮操作-番外篇(详解教程)
【4月更文挑战第28天】本文简要介绍了自动化测试的实战应用,通过一个在线问卷调查(&lt;https://www.sojump.com/m/2792226.aspx/&gt;)为例,展示了如何遍历并点击问卷中的选项。测试思路包括找到单选和多选按钮的共性以定位元素,然后使用for循环进行点击操作。代码设计方面,提供了Java+Selenium的示例代码,通过WebDriver实现自动答题。运行代码后,可以看到控制台输出和浏览器的相应动作。文章最后做了简单的小结,强调了本次实践是对之前单选多选操作的巩固。
22 0
|
8天前
|
SQL JSON DataWorks
DataWorks操作报错合集之DataWorks报错显示API不存在,但这个API应该是有的,如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
24 2
|
10天前
|
设计模式 Java API
Java 可扩展 API 设计:打造灵活的应用架构
【4月更文挑战第27天】设计可扩展的 API 是构建灵活、易于维护的应用程序架构的关键。Java 提供了丰富的工具和技术来实现这一目标,使开发者能够构建具有高度可扩展性的应用程序。
31 4
|
6天前
|
XML 前端开发 Oracle
16:JSP简介、注释与Scriptlet、Page指令元素、Include操作、内置对象、四种属性-Java Web
16:JSP简介、注释与Scriptlet、Page指令元素、Include操作、内置对象、四种属性-Java Web
10 2
|
6天前
|
分布式计算 Java API
Java 8新特性之Lambda表达式与Stream API
【5月更文挑战第1天】本文将介绍Java 8中的两个重要特性:Lambda表达式和Stream API。Lambda表达式是一种新的函数式编程语法,可以简化代码并提高可读性。Stream API是一种用于处理集合的新工具,可以方便地进行数据操作和转换。通过结合Lambda表达式和Stream API,我们可以更加简洁高效地编写Java代码。
|
7天前
|
存储 NoSQL 安全
java 中通过 Lettuce 来操作 Redis
java 中通过 Lettuce 来操作 Redis
java 中通过 Lettuce 来操作 Redis
|
8天前
|
分布式计算 DataWorks 关系型数据库
DataWorks操作报错合集之在DataWorks同步数据时,遇到乱码问题,该怎么解决(rest api数据源)
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
20 0
|
8天前
|
分布式计算 DataWorks 监控
DataWorks操作报错合集之DataWorks在调用java sdk的createFile功能时报错com.aliyuncs.exceptions.ClientException: 1201111000 如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
10 1
|
8天前
|
存储 缓存 运维
DataWorks操作报错合集之DataWorks根据api,调用查询文件列表接口报错如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
20 1