侧边栏壁纸
博主头像
DJ's Blog博主等级

行动起来,活在当下

  • 累计撰写 133 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

【Zookeeper】Java客户端

Administrator
2022-04-04 / 0 评论 / 0 点赞 / 59 阅读 / 5064 字

【Zookeeper】Java客户端

API介绍

地址:http://zookeeper.apache.org/doc/r3.4.6/api/index.html

org.apache.zookeeper.Zookeeper是客户端入口主类,负责建立与server的会话,它提供了下面几类主要方法

功能描述
create在本地目录树中创建一个节点
delete删除一个节点
exists测试本地是否存在目标节点
get/setData从目标节点上读取/写数据
get/setACL获取/设置目标节点访问控制列表信息
getChildren获取某一个节点下所有子节点的列表
sync等待要被传送的数据

示例代码

创建会话

/**
 * 使用SessionId和SessionPasswd创建zookeeper会话
 * @author dj4817
 * @version $Id: ZookeeperWatcher.java, v 0.1 2018/3/12 13:44 dj4817 Exp $$
 */
public class ZooKeeperConstructorUsageWithSIDPASSWD implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    /**
     * 测试使用SessionId和SessionPasswd创建zookeeper会话
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        ZooKeeper zookeeper = new ZooKeeper(Constants.connectString, Constants.sessionTimeout, new ZooKeeperConstructorUsageWithSIDPASSWD());
        connectedSemaphore.await();
        long sessionId = zookeeper.getSessionId();
        byte[] passwd = zookeeper.getSessionPasswd();
        System.out.println("sessionId=" + sessionId + "; passwd=" + passwd.toString());

        //Use illegal sessionId and sessionPassWd
        new ZooKeeper(Constants.connectString, Constants.sessionTimeout, new ZooKeeperConstructorUsageWithSIDPASSWD(), 1L, "test".getBytes());
        //Use correct sessionId and sessionPassWd
        new ZooKeeper(Constants.connectString, Constants.sessionTimeout, new ZooKeeperConstructorUsageWithSIDPASSWD(), sessionId, passwd);
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * 异步通知处理
     * @param event
     */
    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event:" + event);
        if (KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

运行结果:

Receive watched event:WatchedEvent state:SyncConnected type:None path:null
sessionId=27939408385212418; passwd=[B@759ebb3d
Receive watched event:WatchedEvent state:Expired type:None path:null
Receive watched event:WatchedEvent state:SyncConnected type:None path:null
  1. 第一次使用错误的sessionIdsessionPasswd来创建Zookeeper客户端的实例,结果客户端接收到了服务端的Expired事件通知;
  2. 第二次使用正确的sessionIdsessionPasswd,连接成功。

创建节点

  1. Zookeeper不支持递归创建节点,即无法在父节点不存在的情况下创建一个子节点。
  2. 如果一个节点已经存在了,那么创建同名节点的时候,会抛出NodeExistsException异常。
/**
 * 使用同步方式创建zookeeper节点
 * @author dj4817
 * @version $Id: ZookeeperWatcher.java, v 0.1 2018/3/12 13:44 dj4817 Exp $$
 */
public class ZooKeeperCreateApiSyncUsage implements Watcher {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    /**
     * 测试使用同步方式创建zookeeper节点
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        ZooKeeper zookeeper = new ZooKeeper(Constants.connectString, Constants.sessionTimeout, new ZooKeeperCreateApiSyncUsage());
        connectedSemaphore.await();
        // Ids.OPEN_ACL_UNSAFE:表明之后这个节点的任何操作都不受权限控制。
        String path1 = zookeeper.create("/zk-test-ephemeral-", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("Success create znode: " + path1);
        String path2 = zookeeper.create("/zk-test-ephemeral-", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("Success create znode: " + path2);
    }

    /**
     * 异步通知处理
     * @param event
     */
    @Override
    public void process(WatchedEvent event) {
        if (KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

运行结果

Success create znode: /zk-test-ephemeral-
Success create znode: /zk-test-ephemeral-0000000001
  1. 如果创建一个临时节点,那么create方法返回当时传入的path参数。
  2. 如果创建一个临时顺序节点,那么Zookeeper会自动在节点后缀加上一个数字,返回create方法返回这个节点的完整路径。
0

评论区