博客
关于我
基于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/

    你可能感兴趣的文章
    npm包管理深度探索:从基础到进阶全面教程!
    查看>>
    npm升级以及使用淘宝npm镜像
    查看>>
    npm发布包--所遇到的问题
    查看>>
    npm发布自己的组件UI包(详细步骤,图文并茂)
    查看>>
    npm和package.json那些不为常人所知的小秘密
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>