当前位置: 首页 > news >正文

ZkClient API使用

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Maven工程方式导入ZkClient API

<dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.10</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>com.101tec</groupId>
      <artifactId>zkclient</artifactId>
      <version>0.10</version>
    </dependency>

create session 创建和zookeeper集群间的连接

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description:
 *
    1)和zookeeper原生API不同,通过zkclient API创建会话,需要提供session timout, connection timeout两个定时器
    2)同时要提供1个序列化器实例,原因在于后续创建znode节点时,写入的数据(java对象)会自动通过序列化器来转换为byte[]
    3)同理,读取出的byte[]的数据,也会自动通过序列化器直接转换为Java对象

 * @time: 2018年06月04日
 * @modifytime:
 */
public class CreateSession {

    public static void main(String[] args) {
        ZkClient zkClient = new ZkClient("192.168.20.157:2181",5000,5000,new SerializableSerializer());

        System.out.println("Connection OK!");

    }
}

创建znode节点

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 添加数据节点
 * @time: 2018年06月04日
 * @modifytime:
 */
public class CreateNode {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());

        User u = new User();
        String actual_path = zc.create("/node_zkclient/ddd", u, CreateMode.PERSISTENT); //直接将实例u写入,自动通过序列化为byte[]
        System.out.println(actual_path);
    }
}

修改节点数据

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 修改数据节点
 * @time: 2018年06月04日
 * @modifytime:
 */
public class NodeSetData {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        User u = new User();
        u.setId(1L);
        u.setName("shayzhang");

        if(!zc.exists("/node_zkclient")){
            zc.create("/node_zkclient",u, CreateMode.PERSISTENT);
        }
        u.setId(2L);
        u.setName("zhangjin");

        zc.writeData("/node_zkclient",u);//直接写入实例,自动通过连接创建时创建的序列化实例,转换为byte[]
    }
}

获取节点数据

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description:
 * @time: 2018年06月04日
 * @modifytime:
 */
public class NodeGetData {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        User u = new User();
        u.setId(1L);
        u.setName("shayzhang");
        String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT);
        System.out.println("Create path is: " + actual_path);

        Stat stat = new Stat();
        zc.readData("/node_zkclient",stat);

        if(u == null){
            System.out.println("Node doesn't exist!");
        }else {
            System.out.println(u.getId());
            System.out.println(stat);
        }
    }
}

获取子节点列表

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 获取子节点列表
 * @time: 2018年06月04日
 * @modifytime:
 */
public class NodeGetChildren {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        if(!zc.exists("/node_zkclient")){
            User u = new User();
            u.setId(1L);
            u.setName("shayzhang");

            String actual_path = zc.create("/node_zkclient", u, CreateMode.PERSISTENT);
            System.out.println("Create path is: " + actual_path);
        }
        List<String> children_list  = zc.getChildren("/node_zkclient");
        System.out.println("Children list of /node_zkclient is : " + children_list.toString());  //打印子节点列表
    }

}

删除节点

package com.timer.zkClientApi;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 删除节点
 * @time: 2018年06月04日
 * @modifytime:
 */
public class NodeDeleteNode {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        String delete_node = "/node_zkclient/abc";

        if(zc.exists(delete_node)){
            //delete node without children
            boolean e1 = zc.delete(delete_node);
            System.out.println("Delete node without children: " + e1);
        }
        // delete node and all children
        boolean e2 = zc.deleteRecursive(delete_node);
        System.out.println("Delete node and children: " + e2);
    }
}

订阅子节点列表发生变化

package com.timer.zkClientApi;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 订阅子节点列表发生变化
 * @time: 2018年06月04日
 * @modifytime:
 */
public class SubscribeChildren {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        System.out.println("Connected to zk server!");
        // subscribe children change event, multiple subscribe
        List<String> results = zc.subscribeChildChanges("/node_zkclient", new ZkChildListener());

        try{
            Thread.sleep(Long.MAX_VALUE);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    private static class ZkChildListener implements IZkChildListener{
        @Override
        public void handleChildChange(String s, List<String> list) throws Exception {
            //print parent path
            System.out.println("Parent path: " + s);
            //print current children
            System.out.println("Current children: " + list.toString());
        }
    }
}

订阅数据变化

package com.timer.zkClientApi;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhubo
 * @description: 订阅数据发生变化
 * @time: 2018年06月04日
 * @modifytime:
 */
public class SubscribeData {

    public static void main(String[] args) {
        ZkClient zc = new ZkClient("192.168.20.157:2181", 5000, 5000, new SerializableSerializer());
        System.out.println("Connected to zk server!");
        // subscribe data change event, multiple subscribe
        zc.subscribeDataChanges("/node_zkclient", new ZkDataListener());
        try{
            Thread.sleep(Long.MAX_VALUE);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    private static class ZkDataListener implements IZkDataListener {
        @Override
        public void handleDataChange(String s, Object o) throws Exception {
            System.out.println("Path Data Changed: " + s);
            System.out.println("Current Data: " + o.toString());
        }
        @Override
        public void handleDataDeleted(String s) throws Exception {
            System.out.println("Data Deleted: " + s);
        }
    }
}

 

 

转载于:https://my.oschina.net/LucasZhu/blog/1824158

相关文章:

  • express + mock 让前后台并行开发
  • Android黑科技: 快速找到view所在的xml文件
  • 30天自制操作系统-2
  • Python运行速度如何?
  • keepalived实现服务高可用
  • js如何遍历表单所有控件
  • Vue.js 2.x笔记:安装与起步(1)
  • Form身份验证
  • Linux常用命令——runlevel、init
  • python爬虫——爬取豆瓣TOP250电影
  • 携程小程序初体验
  • java虚拟机之垃圾回收算法
  • 10分钟了解JS堆、栈以及事件循环的概念
  • 常见面试题—css实现垂直水平居中
  • hyperLedger fabric 从0到1 + End2EndIT源码解析
  • 2017 年终总结 —— 在路上
  • Angular4 模板式表单用法以及验证
  • extjs4学习之配置
  • Java方法详解
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • k8s如何管理Pod
  • PV统计优化设计
  • Yii源码解读-服务定位器(Service Locator)
  • 解决jsp引用其他项目时出现的 cannot be resolved to a type错误
  • 鱼骨图 - 如何绘制?
  • ​LeetCode解法汇总1276. 不浪费原料的汉堡制作方案
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • #Z0458. 树的中心2
  • (31)对象的克隆
  • (AngularJS)Angular 控制器之间通信初探
  • (C语言)字符分类函数
  • (pojstep1.1.2)2654(直叙式模拟)
  • (Redis使用系列) Springboot 使用Redis+Session实现Session共享 ,简单的单点登录 五
  • (六)激光线扫描-三维重建
  • (牛客腾讯思维编程题)编码编码分组打印下标(java 版本+ C版本)
  • (求助)用傲游上csdn博客时标签栏和网址栏一直显示袁萌 的头像
  • (十一)JAVA springboot ssm b2b2c多用户商城系统源码:服务网关Zuul高级篇
  • (一)SpringBoot3---尚硅谷总结
  • (转)mysql使用Navicat 导出和导入数据库
  • (转)菜鸟学数据库(三)——存储过程
  • (最优化理论与方法)第二章最优化所需基础知识-第三节:重要凸集举例
  • *上位机的定义
  • .mkp勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .net和php怎么连接,php和apache之间如何连接
  • .net中的Queue和Stack
  • /etc/sudoers (root权限管理)
  • [2017][note]基于空间交叉相位调制的两个连续波在few layer铋Bi中的全光switch——
  • [C#]无法获取源 https://api.nuge t.org/v3-index存储签名信息解决方法
  • [CF482B]Interesting Array
  • [IOI2018] werewolf 狼人
  • [JS] node.js 入门
  • [NISACTF 2022]join-us
  • [node]Node.js 模块系统
  • [RoarCTF 2019]PHPShe