zookeeper-curator

Curator_Start

package test.ygy.curator;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/27.
 */
public class Curator_Start {

    private static final Logger log = LoggerFactory.getLogger(Curator_Start.class);

    public static final String CONNECT_STRING="192.168.150.130:2181,192.168.150.132:2181,192.168.150.133:2181";

    public static final  String CONNECT_STRING_YGY = "www.ygy.com:2181";

    public static final  int SESSION_TIMEOUT_MS = 5000;

    public static final  int CONNECTION_TIMEOUT_MS  = 5000 ;


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


        //public static CuratorFramework newClient(
        // String connectString,   //服務器連接地址
        // int sessionTimeoutMs,   //會話超時時間,單位爲毫秒 默認60000
        // int connectionTimeoutMs,  //連接創建超時時間,單位爲毫秒。
        // RetryPolicy retryPolicy) {  //重試策略接口
        //public boolean      allowRetry(int retryCount,   //已經重試的次數
        // long elapsedTimeMs,  //從第一次重試開始已經花費的時間,單位毫秒
        // RetrySleeper sleeper);  //用於sleep指定的時間

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        //public ExponentialBackoffRetry(int baseSleepTimeMs,   初始sleep時間
        // int maxRetries,      最大重試次數
        // int maxSleepMs)      最大sleep時間
        // copied from Hadoop's RetryPolicies.java  ExponentialBackoffRetry 睡眠策略
        //long sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)));
        // sleepMs 將不會超過最大sleep時間

        //CuratorFramework curatorFramework=CuratorFrameworkFactory.newClient(
        //        CONNECT_STRING, SESSION_TIMEOUT_MS, CONNECTION_TIMEOUT_MS, retryPolicy);

        //fluent風格
        CuratorFramework curatorFramework=CuratorFrameworkFactory.builder()
                .connectString(CONNECT_STRING)
                .sessionTimeoutMs(SESSION_TIMEOUT_MS)
                .connectionTimeoutMs(CONNECTION_TIMEOUT_MS)
                .namespace("isolation")   //不同的命名空間,隔離zookeeper業務,互不干擾
                .retryPolicy(retryPolicy).build();

        curatorFramework.start();
        log.warn(" 啓動成功");

        Thread.sleep(10000000);
        curatorFramework.close();
    }

    public static CuratorFrameworkFactory.Builder getYGYBuilder() {
        return  CuratorFrameworkFactory.builder()
                .connectString(CONNECT_STRING_YGY)
                .sessionTimeoutMs(SESSION_TIMEOUT_MS)
                //.connectionTimeoutMs(CONNECTION_TIMEOUT_MS)
                .retryPolicy(new ExponentialBackoffRetry(1000,3));
    }

    public static CuratorFrameworkFactory.Builder getBaseBuilder() {
        return  CuratorFrameworkFactory.builder()
                .connectString(CONNECT_STRING)
                .sessionTimeoutMs(SESSION_TIMEOUT_MS)
                //.connectionTimeoutMs(CONNECTION_TIMEOUT_MS)
                .retryPolicy(new ExponentialBackoffRetry(1000,3));
    }
}

Curator_Crud

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/27.
 */
public class Curator_Crud {

    private static final Logger log=LoggerFactory.getLogger(Curator_Crud.class);

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

        CuratorFramework cf=Curator_Start.getBaseBuilder().build();

        cf.start();
        log.warn(" zookeeper 啓動成功");


        //創建節點  默認創建持久節點,節點數據默認爲空
        //************* 報錯KeeperErrorCode = ConnectionLoss for /zk-test  curator 與 服務器版本衝突
        //cf.create().forPath("/zk-test");

        //遞歸創建
        //cf.create().creatingParentsIfNeeded()   //如果父節點不存在 遞歸創建
        //        .withMode(CreateMode.PERSISTENT)    //指定節點類型
        //        .forPath("/test/child", "init".getBytes());   //初始化值  /test:空  test/child:init

        //刪除節點
        //cf.delete().forPath("/test/child");

        //遞歸刪除當前節點及當前節點的所有子節點
        //cf.delete().guaranteed()    //只要當前會話內,curator會在後臺持續進行刪除,直到節點被刪除
        //        .deletingChildrenIfNeeded()
        //        .forPath("/test");

        //獲取節點數據
        //byte[] bytes=cf.getData().forPath("/test");
        //log.warn(" /test 's data is " + new String(bytes));
        //23:37:09.563 [main] WARN test.ygy.curator.Curator_Crud -  /test 's data is 1111

        //獲取節點數據,同時獲取stat(服務器創建新stat替換原stat)
        //Stat oldStat = new Stat() ;
        //byte[] bytes=cf.getData().storingStatIn(oldStat).forPath("/test");
        //log.warn(" stat  =" + oldStat);
        //23:39:20.694 [main] WARN test.ygy.curator.Curator_Crud -  stat  =21474836550,21474836550,1503848137880,1503848137880,0,0,0,0,4,0,21474836550


        //更新節點數據
        Stat stat=cf.setData()
                .withVersion(-1)  //根據版本信息來修改,可從stat中獲取實現cas
                .forPath("/test", "new data ".getBytes());
        log.warn(" updated  stat = " + stat);
        //23:45:05.168 [main] WARN test.ygy.curator.Curator_Crud -  updated  stat = 21474836550,21474836556,1503848137880,1503848704703,1,0,0,0,9,0,21474836550

        Thread.sleep(2000);


        cf.close();

    }
}

Cruator_BackGround

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by guoyao on 2017/8/27.
 */
public class Cruator_BackGround {

    private  static  final Logger log =LoggerFactory.getLogger(Cruator_BackGround.class);

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

        ExecutorService executorService=Executors.newFixedThreadPool(2);
        CountDownLatch countDownLatch=new CountDownLatch(4);

        CuratorFramework cf=Curator_Start.getBaseBuilder().build();
        cf.start();
        log.warn(" zookeeper 啓動成功");
        Thread.sleep(10000);
        //使用線程池
        cf.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .inBackground(
                        (x, y) -> {   //x ,y : CuratorFramework client 客戶端  CuratorEvent event事件
                            log.warn(" event = " + y);
                            log.warn(" execcutors threadName = " + Thread.currentThread().getName());
                            countDownLatch.countDown();
                        }
                ,executorService).forPath("/test", "test back".getBytes());
        //00:28:38.572 [pool-1-thread-1] WARN test.ygy.curator.Cruator_BackGround -  event = CuratorEventImpl{type=CREATE, resultCode=0, path='/test', name='/test', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null}
        //00:28:38.572 [pool-1-thread-1] WARN test.ygy.curator.Cruator_BackGround -  execcutors threadName = pool-1-thread-1

        cf.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .inBackground(
                        (x, y) -> {   //x ,y : CuratorFramework client 客戶端  CuratorEvent event事件
                            log.warn(" event = " + y);
                            log.warn(" execcutors threadName = " + Thread.currentThread().getName());
                            countDownLatch.countDown();
                        }
                        ,executorService).forPath("/test", "test back".getBytes());
        //00:28:38.621 [pool-1-thread-2] WARN test.ygy.curator.Cruator_BackGround -  event = CuratorEventImpl{type=CREATE, resultCode=-110, path='/test', name='null', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null}
        //00:28:38.622 [pool-1-thread-2] WARN test.ygy.curator.Cruator_BackGround -  execcutors threadName = pool-1-thread-2

        //不使用線程池,默認使用main-EventThread ,多個事件默認時,是嚴格按照順序執行。
        cf.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .inBackground(
                        (x, y) -> {   //x ,y : CuratorFramework client 客戶端  CuratorEvent event事件
                            log.warn(" event = " + y);
                            log.warn(" execcutors threadName = " + Thread.currentThread().getName());
                            countDownLatch.countDown();
                        }
                ).forPath("/test", "test back".getBytes());
        //00:28:38.622 [main-EventThread] WARN test.ygy.curator.Cruator_BackGround -  event = CuratorEventImpl{type=CREATE, resultCode=-110, path='/test', name='null', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null}
        //00:28:38.622 [main-EventThread] WARN test.ygy.curator.Cruator_BackGround -  execcutors threadName = main-EventThread

        cf.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .inBackground(
                        (x, y) -> {   //x ,y : CuratorFramework client 客戶端  CuratorEvent event事件
                            log.warn(" event = " + y);
                            log.warn(" execcutors threadName = " + Thread.currentThread().getName());
                            countDownLatch.countDown();
                        }
                ).forPath("/test", "test back".getBytes());
        //00:28:38.623 [main-EventThread] WARN test.ygy.curator.Cruator_BackGround -  event = CuratorEventImpl{type=CREATE, resultCode=-110, path='/test', name='null', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null}
        //00:28:38.623 [main-EventThread] WARN test.ygy.curator.Cruator_BackGround -  execcutors threadName = main-EventThread

        countDownLatch.await();

        Thread.sleep(10000);
        executorService.shutdown();
        cf.close();
    }
}

Curator_NodeCacheListener

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * Created by guoyao on 2017/8/28.
 */
public class Curator_NodeCacheListener {

    private static final Logger log=LoggerFactory.getLogger(Curator_NodeCacheListener.class);

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

        CountDownLatch countDownLatch=new CountDownLatch(1);

        CuratorFramework cf=Curator_Start.getYGYBuilder().build();
        cf.start();
        log.warn(" zookeeper  啓動成功");

        //創建一個節點
        cf.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath("/test", "init".getBytes());

        //nodeCache  client :客戶端  path : 節點路徑  dataIsCompressed : 是否壓縮
        NodeCache nodeCache=new NodeCache(cf, "/test", false);
        nodeCache.start(true);
        // nodeCache 可以監聽指定節點數據變化,與節點是否存在
        nodeCache.getListenable().addListener(
                ()->{
                    log.warn("data changed to " + new String(nodeCache.getCurrentData().getData()));
                    countDownLatch.countDown();
                }
        );

        //設置新值,
        cf.setData().forPath("/test", " new data ".getBytes());
        countDownLatch.await();
        cf.delete().forPath("/test");


        Thread.sleep(20000);
        cf.close();
    }
}

Curator_PathChildrenListener

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/29.
 */
public class Curator_PathChildrenListener {

    private static final Logger log=LoggerFactory.getLogger(Curator_PathChildrenListener.class);

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

        CuratorFramework cf=Curator_Start.getYGYBuilder().build();
        cf.start();
        log.warn(" zookeepeer  啓動成功");

        /**
         * @param client           the client  客服端
         * @param path             path to watch  節點路徑
         * @param cacheData        if true, node contents are cached in addition to the stat  是否需要獲取節點數據
         * @param dataIsCompressed if true, data in the path is compressed  是否壓縮
         * @param executorService  Closeable ExecutorService to use for the PathChildrenCache's background thread
         */

        // 默認線程池爲守護線程  主線程執行完畢即停止
        //return (new ThreadFactoryBuilder()).setNameFormat(processName + "-%d").setDaemon(true).build();
        PathChildrenCache pathChildrenCache=new PathChildrenCache(
                cf,
                "/test",
                true
        );
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pathChildrenCache.getListenable().addListener(
                new PathChildrenCacheListener() {
                    @Override
                    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                        switch (event.getType()) {
                            //10:33:44.078 [PathChildrenCache-0] WARN test.ygy.curator.Curator_PathChildrenListener -  INITIALIZED 初始化
                            case INITIALIZED:
                                log.warn(" INITIALIZED 初始化");
                                break;
                            // 10:33:45.955 [PathChildrenCache-0] WARN test.ygy.curator.Curator_PathChildrenListener -  CHILD_ADDED 新增子節點 ChildData{path='/test/child1', stat=70,70,1503974025843,1503974025843,0,0,0,98542789669486605,11,0,70
                            //, data=[116, 101, 115, 116, 32, 99, 104, 105, 108, 100, 49]}
                            case CHILD_ADDED:
                                log.warn(" CHILD_ADDED 新增子節點 " + event.getData());
                                break;
                            //10:33:54.062 [PathChildrenCache-0] WARN test.ygy.curator.Curator_PathChildrenListener -  CHILD_REMOVED 移除子節點ChildData{path='/test/child3', stat=72,72,1503974029930,1503974029930,0,0,0,98542789669486605,11,0,72
                            // , data=[116, 101, 115, 116, 32, 99, 104, 105, 108, 100, 51]}
                            case CHILD_REMOVED:
                                log.warn(" CHILD_REMOVED 移除子節點" + event.getData());
                                break;
                            //10:33:52.056 [PathChildrenCache-0] WARN test.ygy.curator.Curator_PathChildrenListener -  CHILD_UPDATED 修改子節點數據ChildData{path='/test/child2', stat=71,73,1503974027885,1503974031986,1,0,0,98542789669486605,15,0,71
                            //, data=[110, 101, 119, 32, 99, 104, 105, 108, 100, 50, 32, 100, 97, 116, 97]}
                            case CHILD_UPDATED:
                                log.warn(" CHILD_UPDATED 修改子節點數據" + event.getData());
                                break;
                            case CONNECTION_LOST:
                                log.warn(" CONNECTION_LOST 確認失去連接");
                                break;
                            case CONNECTION_SUSPENDED:
                                log.warn(" CONNECTION_SUSPENDED 連接掛起,可能失去連接");
                                break;
                            case CONNECTION_RECONNECTED:
                                log.warn(" CONNECTION_RECONNECTED 重新獲取連接");
                                break;
                            default:
                                break;
                        }
                    }
                }
        );
        //報錯 pathChildrenCache 構造方法中已經會確保該path 被創建
        //cf.create().withMode(CreateMode.PERSISTENT).forPath("/test", "test".getBytes());
        Thread.sleep(2000);
        cf.create().withMode(CreateMode.EPHEMERAL).forPath("/test/child1", "test child1".getBytes());
        Thread.sleep(2000);
        cf.create().withMode(CreateMode.EPHEMERAL).forPath("/test/child2", "test child2".getBytes());
        Thread.sleep(2000);
        cf.create().withMode(CreateMode.EPHEMERAL).forPath("/test/child3", "test child3".getBytes());
        Thread.sleep(2000);
        cf.setData().forPath("/test/child2", "new child2 data".getBytes());
        Thread.sleep(2000);
        cf.delete().forPath("/test/child3");
        Thread.sleep(20000);
        cf.close();
    }
}

Cruator_LeaderSelector

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.utils.EnsurePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/28.
 */
//leader選舉
public class Cruator_LeaderSelector {

    private static final Logger log=LoggerFactory.getLogger(Cruator_LeaderSelector.class);

    private static final String MASTER_PATH="/curator-master";

    public static void main(String[] args) throws  Exception {
        CuratorFramework cf=Curator_Start.getBaseBuilder().build();
        cf.start();
       log.warn(" zookeeper  啓動成功");

        //保證節點存在
        new EnsurePath(MASTER_PATH+"/AAAA").ensure(cf.getZookeeperClient());
        //   * @param client          the client  客戶端
     //  * @param leaderPath      the path for this leadership group  節點路徑
     //* @param executorService thread pool to use   線程池
     // * @param listener        listener   監聽器
        LeaderSelector leaderSelector = new LeaderSelector(
                cf
                , MASTER_PATH
                , new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {

                log.warn(" i am master ");
                Thread.sleep(3000);
                log.warn(" off master ");
            }
        });
        leaderSelector.autoRequeue();
        leaderSelector.start();

        Thread.sleep(200000000);
        cf.close();
    }
}

Curator_Atomic

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.RetryNTimes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/29.
 */
public class Curator_Atomic {

    private static final Logger log=LoggerFactory.getLogger(Curator_Atomic.class);

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

        CuratorFramework cf=Curator_Start.getBaseBuilder().build();
        cf.start();
        log.warn("  zookeeper 啓動成功");

        DistributedAtomicInteger distributedAtomicInteger=
                new DistributedAtomicInteger(cf, "/test/atomic", new RetryNTimes(3, 2000));
        AtomicValue<Integer> increment1=distributedAtomicInteger.increment();
        log.warn("  atomic post inc1 = " + increment1.postValue());
        log.warn("  atomic pre inc1 = " + increment1.preValue());
        //22:32:31.193 [main] WARN test.ygy.curator.Curator_Atomic -   atomic post inc1 = 1
        //22:32:31.193 [main] WARN test.ygy.curator.Curator_Atomic -   atomic pre inc1 = 0
        AtomicValue<Integer> increment2=distributedAtomicInteger.increment();
        log.warn("  atomic post inc2 = " + increment2.postValue());
        log.warn("  atomic pre inc2 = " + increment2.preValue());
        //22:32:31.212 [main] WARN test.ygy.curator.Curator_Atomic -   atomic post inc2 = 2
        //22:32:31.212 [main] WARN test.ygy.curator.Curator_Atomic -   atomic pre inc2 = 1


        Thread.sleep(20000);
        cf.close();
    }
}

Cruator_InterLock

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by guoyao on 2017/8/28.
 */
public class Cruator_InterLock {

    private static final Logger log=LoggerFactory.getLogger(Cruator_InterLock.class);

    private  static  int index = 0 ;

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

        CuratorFramework cf=Curator_Start.getBaseBuilder().build();
        cf.start();
        log.warn(" zookeeper  啓動成功");
        ExecutorService executorService=Executors.newFixedThreadPool(100);
        CountDownLatch countDownLatch=new CountDownLatch(100);

        //zookeeper 鎖
        InterProcessMutex interProcessMutex=new InterProcessMutex(cf,"/test/lock");
        for (int i=0; i < 100; i++) {
            executorService.execute(()->{
                try {
                    Thread.sleep(1000);
                    interProcessMutex.acquire();
                    index++;
                    interProcessMutex.release();
                    countDownLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                    countDownLatch.countDown();
                }
            });
        }
        executorService.shutdown();
        countDownLatch.await();
        log.warn("   index add 100 times = " + index);

    }
}

Curator_Barrier

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/29.
 */
public class Curator_Barrier {

    private static final Logger log=LoggerFactory.getLogger(Curator_Barrier.class);

    public static void main(String[] args) throws Exception {
        CuratorFramework cf=Curator_Start.getBaseBuilder().build();
        cf.start();
        log.warn(" zookeeper 啓動成功");


        DistributedBarrier distributedBarrier = new DistributedBarrier(cf,"/test/barries");
        DistributedAtomicInteger distributedAtomicInteger=
                new DistributedAtomicInteger(cf, "/test/ato", new RetryNTimes(3, 2000));
        //cf.create().creatingParentsIfNeeded().forPath("/test/barries");
        Stat stat1=cf.checkExists().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {

            }
        }).forPath("/test/barries");
        log.warn(" check  stat1 = " + stat1);

        for(int i = 0 ; i < 10 ; i ++) {
            new Thread(
                    ()->{
                        try {
                            distributedBarrier.setBarrier();   //設置柵欄
                            Thread.sleep(1000);
                            log.warn(Thread.currentThread().getName() + " is waiting");
                            distributedAtomicInteger.increment();  //計數
                            distributedBarrier.waitOnBarrier();   //無線等待
                            //do work
                            Thread.sleep(2000);
                            log.warn(Thread.currentThread().getName() + " is running");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    ," thread -- " + i).start();
        }
        int index = 0 ;
        while (distributedAtomicInteger.get().postValue() < 10) {

            //等待所有任務進入
            if (index < distributedAtomicInteger.get().postValue()) {
                log.warn(" 當前已備註數爲 " + distributedAtomicInteger.get().postValue());
                index = distributedAtomicInteger.get().postValue();
            }

        }
        Stat stat2=cf.checkExists().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {

            }
        }).forPath("/test/barries");
        log.warn(" check  stat2 = " + stat2);
        distributedBarrier.removeBarrier();
        Stat stat3=cf.checkExists().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {

            }
        }).forPath("/test/barries");
        log.warn(" check  stat3 = " + stat3);


        Thread.sleep(100000);
        cf.close();
    }
}

Curator_Barray_Double

package test.ygy.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by guoyao on 2017/8/30.
 */
public class Curator_Barray_Double {

    private static final Logger log=LoggerFactory.getLogger(Curator_Barray_Double.class);

    public static void main(String[] args) throws Exception {
        CuratorFramework cf=Curator_Start.getYGYBuilder().build();
        cf.start();
        log.warn(" zookeeper 啓動成功");
        for(int i = 0 ; i < 10 ; i ++) {
            new Thread(
                    ()->{
                        try {
                            log.warn(Thread.currentThread().getName() + " is waiting");
                            // 由ourPath 控制個數,需要每次都new一個對象
                            DistributedDoubleBarrier distributedDoubleBarrier = new DistributedDoubleBarrier(cf,"/test/barries",5);
                            distributedDoubleBarrier.enter();   //設置柵欄
                            Thread.sleep(1000);
                            //do work
                            log.warn(Thread.currentThread().getName() + " is working");
                            distributedDoubleBarrier.leave();   //退出
                            log.warn(Thread.currentThread().getName() + " is out");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    ," thread -- " + i).start();
        }

        Thread.sleep(100000);
        cf.close();


    }
}
發佈了72 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章