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

    你可能感兴趣的文章
    nessus快速安装使用指南(非常详细)零基础入门到精通,收藏这一篇就够了
    查看>>
    Nessus漏洞扫描教程之配置Nessus
    查看>>
    Nest.js 6.0.0 正式版发布,基于 TypeScript 的 Node.js 框架
    查看>>
    Netpas:不一样的SD-WAN+ 保障网络通讯品质
    查看>>
    netsh advfirewall
    查看>>
    Netty WebSocket客户端
    查看>>
    Netty 异步任务调度与异步线程池
    查看>>
    Netty中集成Protobuf实现Java对象数据传递
    查看>>
    Netty工作笔记0006---NIO的Buffer说明
    查看>>
    Netty工作笔记0011---Channel应用案例2
    查看>>
    Netty工作笔记0013---Channel应用案例4Copy图片
    查看>>
    Netty工作笔记0014---Buffer类型化和只读
    查看>>
    Netty工作笔记0020---Selectionkey在NIO体系
    查看>>
    Vue踩坑笔记 - 关于vue静态资源引入的问题
    查看>>
    Netty工作笔记0025---SocketChannel API
    查看>>
    Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
    查看>>
    Netty工作笔记0050---Netty核心模块1
    查看>>
    Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
    查看>>
    Netty工作笔记0077---handler链调用机制实例4
    查看>>
    Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
    查看>>