wuliws 发表于 2019-1-8 09:22:57

客户端操作zookeeper服务代码示例

  本文主要贴出通过zookeeper的客户端类访问zookeeper的示例,以及其它第三方更高层次的封装的客户端使用。
  

  1.通过org.apache.zookeeper.ZooKeeper来操作zookeeper服务
  有关zookeeper服务的部署参见文:http://aiilive.blog.运维网.com/1925756/1684145 下文将有代码示例展示通过编码方式在应用中启动zookeeper服务。
  ZooKeeper类对zookeeper服务的简单操作示例代码如下:
package secondriver.dubbo.client;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Author : secondriver
*/
public class TestZookeeper {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
      //创建zookeeper客户端
      ZooKeeper zooKeeper = new ZooKeeper("192.168.88.153:2181", 1000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("EventType:" + event.getType().name());
            }
      });
      //获取"/" node下的所有子node
      List znodes = zooKeeper.getChildren("/", true);
      for (String path : znodes) {
            System.out.println(path);
      }
      //创建开放权限的持久化node "/test"
      String rs = zooKeeper.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode
                .PERSISTENT);
      System.out.println(rs);
      //同步获取"/test" node的数据
      Stat stat = new Stat();
      byte[] data = zooKeeper.getData("/test", true, stat);
      System.out.println("value=" + new String(data));
      System.out.println(stat.toString());

      //异步获取"/test" node的数据
      zooKeeper.getData("/test", true, new AsyncCallback.DataCallback() {
            @Override
            public void proce***esult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                System.out.println(rc);
                System.out.println(path);
                System.out.println(ctx);
                System.out.printf(new String(data));
                System.out.println(stat.toString());
            }
      }, "Object ctx ..(提供的外部对象)");
      TimeUnit.SECONDS.sleep(10);
      zooKeeper.close();
    }
}  

  上述代码依赖zookeeper包

    org.apache.zookeeper
    zookeeper
    3.4.6
  

  2.通过zkclient操作zookeeper服务
  zkclient github: https://github.com/sgroschupf/zkclient
  后续有二次开发的版本:
  项目: https://github.com/adyliu/zkclient
  文档: https://github.com/adyliu/zkclient/wiki/tutorial
  下文代码示例使用sgroschupf/zkclient,依赖Zookeeper包。
  mavensgroschupf/zkclient

    com.101tec
    zkclient
    0.5
  

  应用内server+client:
package secondriver.dubbo.server;
import org.I0Itec.zkclient.IDefaultNameSpace;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkServer;
import org.apache.zookeeper.CreateMode;
import java.io.IOException;
/**
* Author : secondriver
*/
public class TestI0ItecZk {
    public static void main(String[] args) throws IOException {
      //Server + Client
      ZkServer zkServer = new ZkServer("D:/data", "D:/log", new IDefaultNameSpace() {
            @Override
            public void createDefaultNameSpace(ZkClient zkClient) {
                zkClient.create("/default", "defalut-name-space", CreateMode.PERSISTENT);
            }
      });
      zkServer.start();
      ZkClient zkClient = zkServer.getZkClient();
      boolean exists = zkClient.exists("/default");
      if (exists) {
            System.out.println("default name space init create succeed.");
      } else {
            System.out.println("default name space init create failed.");
      }
      System.in.read();
      zkClient.close();
      zkServer.shutdown();
    }
}  应用外部署server,使用client访问:
package secondriver.dubbo.server;
import org.I0Itec.zkclient.ZkClient;
import java.util.List;
/**
* Author : secondriver
*/
public class TestZkClient {
    public static void main(String[] args) {
      //Only use client
      ZkClient zkc = new ZkClient("192.168.88.153:2181,192.168.88.153:2182,192.168.88.153:2183");
      List childrens = zkc.getChildren("/");
      for (String child : childrens) {
            System.out.println(child);
      }
    }
}  

  下文代码示例使用adyliu/zkclient,同样依赖Zookeeper包,启动Zookeeper服务并做操作。

  maven adyliu/zkclient:

    com.github.adyliu
    zkclient
    2.1.1
package secondriver.dubbo.server;
import com.github.zkclient.*;
import java.io.IOException;
import java.util.List;
/**
* Author : secondriver
*/
public class TestZk {

    public static void main(String[] args) throws IOException {
      String home = System.getProperty("user.home");
      //创建zookeeper服务并启动
      ZkServer zkServer = new ZkServer(home + "/zookeeper/data", home + "/zookeeper/log", 2181);
      zkServer.start();
      //方式一
//      ZkClient zkClient = new ZkClient("127.0.0.1:2181", 1000);
      //方式二
      ZkClient zkClient = zkServer.getZkClient();
      String path = "/test" + Math.random();
      //数据监听
      final IZkDataListener dataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, byte[] data) throws Exception {
                System.out.println(dataPath + " data change");
            }
            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
            }
      };
      //结点(node)监听
      final IZkChildListener childListener = new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List currentChildren) throws Exception {
                System.out.println(parentPath + " parentPath");
                for (String path : currentChildren) {
                  System.out.println(path);
                }
            }
      };
      //为指定node添加监听
      zkClient.subscribeDataChanges(path, dataListener);
      zkClient.subscribeChildChanges("/", childListener);
      //zkclient操作Zookeeper服务
      ///检测node是否存在
      if (zkClient.exists("/zookeeper")) {
            System.out.println("Exist zookeeper path");
      } else {
            System.out.println("Not Exist zookeeper path");
      }
      zkClient.createPersistent(path, path.getBytes());
      byte[] before = zkClient.readData(path);
      System.out.println("before:" + new String(before));
      //以原子的方式更新指定的path node的数据
      zkClient.cas(path, new IZkClient.DataUpdater() {
            @Override
            public byte[] update(byte[] currentData) {
                return new String(currentData).concat(new String(" updated")).getBytes();
            }
      });
      byte[] after = zkClient.readData(path);
      System.out.println("after:" + new String(after));
      //取消指定path node的数据监听
      zkClient.unsubscribeDataChanges(path, dataListener);
      zkClient.writeData(path, "new-data".getBytes());
      byte[] dataBytes = zkClient.readData(path);
      String data = new String(dataBytes);
      System.out.println(path + " data :" + data);
      System.in.read();
      zkClient.close();
      zkServer.shutdown();
    }
}  

  3. Zookeeper客户端和富Zookeeper框架之curator

  github: https://github.com/Netflix/curator
  已成为apache项目:http://curator.apache.org



页: [1]
查看完整版本: 客户端操作zookeeper服务代码示例