Curator中提供了一系列Fluent风格的接口,开发人员可以通过对其进行自由组合来完成各种类型节点的创建。

Curator创建节点的API

  • CuratorFramework
    • public CreateBuilder create();
  • CreateBuilder
    • public ProtectACLCreateModePathAndBytesable<String> createParentsIfNeeded();
  • CreateModable
    • public T withMode(CreateMode mode);
  • PathAndBytesable<T>
    • public T forPath(String path, byte[] data) throws Exception;
    • public T forPath(String path) throws Exception;

        以上就是一系列最常用的创建节点API。下面通过一些场景来说明如何使用这些API。

创建一个节点,初始内容为空

client.create().forPath(path);

注意,如果没有设置节点属性,那么Curator默认创建的是持久节点,内容默认是空。这里的client是指一个已经完成会话创建并启动的Curator客户端实例,即CuratorFramework对象实例。

创建一个节点,附带初始内容

client.create.forPath(path, "init".getBytes());

也可以在创建节点的时候写入初始节点内容。和ZkClient不同的是,Curator仍然是按照ZooKeeper原生API的风格,使用byte[]作为方法参数。

创建一个临时节点,初始内容为空

client.create().withMode(CreateMode.EPHEMERAL).forPath(path);

创建一个临时节点,并自动递归创建父节点

client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);

这个接口非常有用,在使用ZooKeeper的过程中,开发人员经常会碰到NoNodeException异常,其中一个可能的原因就是试图对一个不存在的父节点创建子节点。因此,开发人员不得不在每次创建节点之前,都判断一下该父节点是否存在——这个处理通常让人厌恶。在使用Curator之后,通过调用creatingParentsIfNeeded接口,Curator就能够自动的递归创建所有需要的父节点。

同时要注意的一点是,由于在ZooKeeper中规定了所有非子节点必须为持久节点,调用上面这个API之后,只有path参数对应的数据节点是临时节点,其父节点均为持久节点。

        下面通过一个实际例子来看看如何在代码中使用这些API。

// 使用Curator创建节点

public class Create_Node_Sample {

static String path = "/zk-book/c1";

static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("domain1.book.zookeeper:2181").sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

public static void main(String[] args) throws Exception {

client.start();

client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());

}

}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐