博客
关于我
基于Apache Curator框架的ZooKeeper基本用法详解
阅读量:159 次
发布时间:2019-02-26

本文共 5544 字,大约阅读时间需要 18 分钟。

基于Apache Curator框架的ZooKeeper基本用法详解

Apache Curator 是一个功能完善的ZooKeeper客户端框架,通过高级API简化了ZooKeeper的操作。它解决了以下三类问题:

  • 封装ZooKeeper client与server之间的连接处理
  • 提供Fluent风格的操作API
  • 封装ZooKeeper的各种应用场景(recipe),如分布式锁服务、集群领导选举、共享计数器、缓存机制、分布式队列等
  • Curator简化了ZooKeeper的使用复杂性

    Curator通过以下几个方面降低了ZooKeeper的复杂性:

  • 重试机制:提供可插拔的重试策略,支持ExponentialBackoffRetry、RetryNTimes、RetryOneTime、RetryUntilElapsed等多种重试方式
  • 连接状态监控:初始化后持续监听ZooKeeper连接状态,自动处理连接变化
  • zk客户端实例管理:管理zk集群连接,必要时重建实例,保证连接可靠性
  • 各种场景支持:实现了ZooKeeper不支持的场景,并遵循最佳实践
  • 基于Curator的ZooKeeper基本用法

    1. 初始化与创建节点

    首先,需要在项目的pom.xml中添加Curator相关依赖:

    org.apache.curator
    curator-framework
    4.0.0
    org.apache.curator
    curator-recipes
    4.0.0
    org.apache.curator
    curator-x-discovery
    4.0.0
    org.apache.curator
    curator-test
    4.0.0
    test

    创建连接实例并初始化:

    import org.apache.curator.RetryPolicy;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.retry.ExponentialBackoffRetry;import org.apache.zookeeper.CreateMode;public class TestApacheCurator {    private static final String SERVER = "192.168.1.159:2100,192.168.1.159:2101,192.168.1.159:2102";    private final int SESSION_TIMEOUT = 30 * 1000;    private final int CONNECTION_TIMEOUT = 3 * 1000;    private CuratorFramework client = null;        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);    @Before    public void init() {        client = CuratorFrameworkFactory.newClient(SERVER, SESSION_TIMEOUT, CONNECTION_TIMEOUT, retryPolicy);        client.start();    }}

    2. 创建节点

    @Testpublic void testCreate() throws Exception {    // 创建永久节点    client.create().forPath("/curator", "/curator data".getBytes());        // 创建有序节点    client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/curator_sequential", "/curator_sequential data".getBytes());        // 创建临时节点    client.create().withMode(CreateMode.EPHEMERAL).forPath("/curator/ephemeral", "/curator/ephemeral data".getBytes());        // 创建有序临时节点    client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/ephemeral_path1", "/curator/ephemeral_path1 data".getBytes());        // 创建带保护的临时有序节点    client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/ephemeral_path2", "/curator/ephemeral_path2 data".getBytes());}

    3. 检查节点是否存在

    @Testpublic void testCheck() throws Exception {    // 检查节点是否存在    Stat stat1 = client.checkExists().forPath("/curator");    Stat stat2 = client.checkExists().forPath("/curator2");        System.out.println("'/curator'是否存在: " + (stat1 != null ? true : false));    System.out.println("'/curator2'是否存在: " + (stat2 != null ? true : false));}

    4. 获取和设置节点数据

    @Testpublic void testGetAndSet() throws Exception {    // 获取节点数据    System.out.println(client.getChildren().forPath("/"));        // 获取节点数据    System.out.println(new String(client.getData().forPath("/curator")));        // 设置节点数据    client.setData().forPath("/curator", "/curator modified data".getBytes());}

    5. 异步设置节点数据及获取通知

    @Testpublic void testSetDataAsync() throws Exception {    // 创建监听器    CuratorListener listener = new CuratorListener() {        @Override        public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {            System.out.println(event.getPath());        }    };        // 添加监听器    client.getCuratorListenable().addListener(listener);        // 异步设置节点数据    client.setData().inBackground().forPath("/curator", "/curator modified data with Async".getBytes());        // 等待异步执行结果    Thread.sleep(10000);}

    6. 删除节点

    @Testpublic void testDelete() throws Exception {    // 创建测试节点    client.create().orSetData().creatingParentContainersIfNeeded().forPath("/curator/del_key1", "/curator/del_key1 data".getBytes());    client.create().orSetData().creatingParentContainersIfNeeded().forPath("/curator/del_key2", "/curator/del_key2 data".getBytes());    client.create().forPath("/curator/del_key2/test_key", "test_key data".getBytes());        // 删除节点    client.delete().forPath("/curator/del_key1");        // 级联删除子节点    client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/curator/del_key2");}

    7. 事务管理

    @Testpublic void testTransaction() throws Exception {    // 定义基本操作    CuratorOp createOp = client.transactionOp().create().forPath("/curator/one_path", "some data".getBytes());    CuratorOp setDataOp = client.transactionOp().setData().forPath("/curator", "other data".getBytes());    CuratorOp deleteOp = client.transactionOp().delete().forPath("/curator");        // 事务执行    List
    results = client.transaction().forOperations(createOp, setDataOp, deleteOp); // 遍历结果 for (CuratorTransactionResult result : results) { System.out.println("执行结果是: " + result.getForPath() + "--" + result.getType()); }}

    8. 命名空间

    @Testpublic void testNamespace() throws Exception {    // 创建命名空间的连接实例    CuratorFramework client2 = CuratorFrameworkFactory.builder()        .namespace("mydemo/v1")        .connectString(SERVER)        .sessionTimeoutMs(SESSION_TIMEOUT)        .connectionTimeoutMs(CONNECTION_TIMEOUT)        .retryPolicy(retryPolicy)        .build();        client2.start();        // 创建带命名空间的节点    client2.create().orSetData().creatingParentContainersIfNeeded().forPath("/server1/method1", "some data".getBytes());        client2.close();}

    通过以上代码示例,可以快速上手Apache Curator框架对ZooKeeper的操作。

    转载地址:http://sdof.baihongyu.com/

    你可能感兴趣的文章
    NTPD使用/etc/ntp.conf配置时钟同步详解
    查看>>
    NTP及Chrony时间同步服务设置
    查看>>
    NTP配置
    查看>>
    NUC1077 Humble Numbers【数学计算+打表】
    查看>>
    NuGet Gallery 开源项目快速入门指南
    查看>>
    NuGet(微软.NET开发平台的软件包管理工具)在VisualStudio中的安装的使用
    查看>>
    nuget.org 无法加载源 https://api.nuget.org/v3/index.json 的服务索引
    查看>>
    Nuget~管理自己的包包
    查看>>
    NuGet学习笔记001---了解使用NuGet给net快速获取引用
    查看>>
    nullnullHuge Pages
    查看>>
    NullPointerException Cannot invoke setSkipOutputConversion(boolean) because functionToInvoke is null
    查看>>
    null可以转换成任意非基本类型(int/short/long/float/boolean/byte/double/char以外)
    查看>>
    Numix Core 开源项目教程
    查看>>
    numpy
    查看>>
    NumPy 或 Pandas:将数组类型保持为整数,同时具有 NaN 值
    查看>>
    numpy 或 scipy 有哪些可能的计算可以返回 NaN?
    查看>>
    numpy 数组 dtype 在 Windows 10 64 位机器中默认为 int32
    查看>>
    numpy 数组与矩阵的乘法理解
    查看>>
    NumPy 数组拼接方法-ChatGPT4o作答
    查看>>
    numpy 用法
    查看>>