07_zookeeper的客户端工具curator

【zk原生api的不足之处】

* 不能自动超时重连,需要手动操作

* watcher事件注册一次后就会失效

* 不支持递归创建节点

【 Apache curator 】

* 解决了watcher的注册一次就失效的问题

* api相对更加简单易用

* 提供更多的解决方案并且实现简单:如分布式锁

* 提供了常用的zk工具类

【实例化zk客户端的多种重试机制】

扫描二维码关注公众号,回复: 3304551 查看本文章
package com.zk.demo;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.*;

/**
 * Created by HigginCui on 2018/9/23.
 */
public class CuratorClient {

    public CuratorFramework client = null;
    public static final String zkServerPath = "127.0.0.1";

    /**
     * 构造方法中实例化zk客户端
     */
    public CuratorClient() {


        /**
         * 同步创建zk示例,原生api是异步的
         * curator连接zk的策略:ExponentialBackoffRetry
         *
         * ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
         *  baseSleepTimeMs:初始sleep的时间
         *  maxRetries:最大重试次数
         *  maxSleepMs:最大充实实际那
         */
        RetryPolicy retryPolicy1 = new ExponentialBackoffRetry(1000, 3);

        /**
         * curator连接zk的策略:RetryNTimes
         *
         * RetryNTimes(int n, int sleepMsBetweenRetries)
         *  n:重试的次数
         *  sleepMsBetweenRetries:每次重试的间隔的时间
         */
        RetryPolicy retryPolicy2 = new RetryNTimes(3, 5000);

        /**
         * curator连接zk的策略:RetryOneTime
         *
         * RetryOneTime(int sleepMsBetweenRetry)
         * sleepMsBetweenRetry:每次重试间隔的时间
         */
        RetryPolicy retryPolicy3 = new RetryOneTime(3000);

        /**
         * curator连接zk的策略:RetryForever
         *
         *  RetryForever(int retryIntervalMs)
         *  永远重试,不推荐
         */
        RetryPolicy retryPolicy4 = new RetryForever(5000);

        /**
         * curator连接zk的策略:RetryUntilElapsed
         *
         * RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
         * maxElapsedTimeMs:最大重试时间
         * sleepMsBetweenRetries:每次重试间隔
         * 重试时间超过maxElapsedTimeMs后,就不在重试
         */
        RetryPolicy retryPolicy5 = new RetryUntilElapsed(2000, 3000);

        client = CuratorFrameworkFactory.builder()
                .connectString(zkServerPath)
                .sessionTimeoutMs(10000)
                .retryPolicy(retryPolicy2)
                .namespace("workspace")
                .build();
        client.start();
    }

    public void closeClient() {
        if (null != client) {
            this.client.close();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/HigginCui/p/9692128.html
今日推荐