zk笔记--使用java客户端访问

来源:互联网 发布:python urlretrieve 编辑:程序博客网 时间:2024/06/05 03:24

 

一:简介

  zk已经跑起来了,接下来就是怎么使用它,让它提供服务,

我使用maven创建工程:依赖如下

    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>   <dependency>  <groupId>org.slf4j</groupId>  <artifactId>slf4j-log4j12</artifactId>  <version>1.7.0</version></dependency><dependency>  <groupId>org.apache.zookeeper</groupId>  <artifactId>zookeeper</artifactId>  <version>3.3.5</version></dependency>

    注意: 依赖中的zk版本是3.3.5这个版本号和启动的zkserver的版本号一致,我使用过高版本的依赖,发现不谦容低版本。

二:demo代码

package com.netboy.netty.zk;import java.io.IOException;import java.util.List;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooDefs.Ids;import org.apache.zookeeper.ZooKeeper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * TODO:   zk客户端的demo, *       实现创建节点,父子节点信息,随机获取子节点信息,删除节点信息功能 *        *    注意: 使用ZK依赖的时候,版本号需要和ZK服务器的版本一样,不然会出现异常,即版本不兼容。本例使用的是3.3.5版本。 *     *   netboy 2013-3-26下午12:57:35 */public class ZkDemo {private static final Logger logger = LoggerFactory.getLogger(ZkDemo.class);private ZooKeeper zk;private String parentDir = "/serverName";private String childDir1 = "/127.0.0.1:8081";private String childDir2 = "/127.0.0.1:8082";private String childDir3 = "/127.0.0.1:8083";/** * 初始化zk连接 *  * @throws IOException */public void init() throws IOException {zk = new ZooKeeper("127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083",1000 * 60, new Watcher() {// 监控所有被触发的事件public void process(WatchedEvent event) {logger.info("已经触发了 {} 事件! ",event.getType());//System.out.println("已经触发了" + event.getType() + "事件!");}});}/** *  从ZK 中获得节点信息,客户端随机获取父目录下的子节点目录,已达到随机均匀的获得主机信息 *  */public void getDirData() throws InterruptedException, KeeperException {int count = 100;int b = 0;int c = 0;int d = 0;String parentDir = "/serverName";List<String> childDir = zk.getChildren(parentDir, true);for(int i = 0; i < count; i++) {int temp = i % 3;switch(temp) {case 0:b++;break;case 1:c++;break;case 2:d++;break;default:break;}logger.info("you get {}th child Node: {} ",                              new Object[]{temp,childDir.get(temp)});Thread.sleep(100);}logger.info("the b = {} the c ={} the d ={} ",                      new Object[]{ b,c,d } );String string = new String(zk.getData(parentDir, false, null));logger.info("the search node is : {} ", string);}/** * 创建父子节点,获得父子节点内容,及父节点下面的所有子节点目录名 *  * @throws KeeperException * @throws InterruptedException */public void createData() throws KeeperException, InterruptedException {//创建父子节点zk.create(parentDir, "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.create(parentDir + childDir1, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.create(parentDir + childDir2, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.create(parentDir + childDir3, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);List<String> childDir = zk.getChildren(parentDir, true);logger.info("the {}  child dir is :{} ", new Object[]{ parentDir,childDir });byte[] object = zk.getData(parentDir, false, null);if(object != null) {String string = new String(object);logger.info("you had created an node ,it is :{} ={} ",new Object[]{ parentDir,string });} else {logger.info("the dir: {} is null", parentDir);}}/** * 删除创建的父子节点 *  * @throws KeeperException * @throws InterruptedException */public void delete() throws InterruptedException, KeeperException {if(zk.exists(parentDir + childDir1, false) != null) {zk.delete(parentDir + childDir1, -1);}if(zk.exists(parentDir + childDir2, false) != null) {zk.delete(parentDir + childDir2, -1);}if(zk.exists(parentDir + childDir3, false) != null) {zk.delete(parentDir + childDir3, -1);}if(zk.exists(parentDir, false) != null) {zk.delete(parentDir, -1);}logger.info("you have deleted the node : {} ", parentDir);}public static void main(String[] args) throws IOException,                         KeeperException, InterruptedException {// 创建一个与服务器的连接ZkDemo demo = new ZkDemo();demo.init();        //如果创建的节点已经存在,就先删除demo.delete();demo.createData();//均匀获得子目录节点信息demo.getDirData();//删除创建的新节点demo.delete();}}


     代码中注释的比较清晰,这里就不在介绍了。


三: 运行

  运行 成功会出现如下日志:




将main函数中的demo.delete();注释掉。重新运行。

使用zk自带的客户端查看:



源码下载链接: ZKclientDemo源码

*************************************************************************************************************************************

Do it,Insist it,Enjoy it


*************************************************************************************************************************************





原创粉丝点击