curator recipes之屏障barrier

Posted lay2017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了curator recipes之屏障barrier相关的知识,希望对你有一定的参考价值。

简介 

当两个进程在执行任务的时候,A调用了B,A需要等待B完成以后的通知,我们可以使用curator的屏障功能来实现。

官方文档:http://curator.apache.org/curator-recipes/barrier.html

JavaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/barriers/DistributedBarrier.html

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Barrier {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 3));
    private static String path = "/barrier/001";
    public static void main(String[] args) throws Exception {
        client.start();
        DistributedBarrier barrier = new DistributedBarrier(client, path);
        barrier.setBarrier();
        System.out.println("set barrier");
        notifyTo();
        System.out.println("wait barrier");
        barrier.waitOnBarrier();
        System.out.println("wait end");
        client.close();
    }

    public static void notifyTo() {
        new Thread(() -> {
            DistributedBarrier barrier = new DistributedBarrier(client, path);
            try {
                System.out.println("notify sleep...");
                Thread.sleep(3000);
                barrier.removeBarrier();
                System.out.println("notify remove barrier");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

输出结果

set barrier
wait barrier
notify sleep...
notify remove barrier
wait end

主线程等待屏障被移除了以后继续执行

 

以上是关于curator recipes之屏障barrier的主要内容,如果未能解决你的问题,请参考以下文章

二十curator recipes之NodeCache

七curator recipes之阻塞队列SimpleDistributedQueue

九curator recipes之不可重入锁InterProcessSemaphoreMutex

十curator recipes之信号量InterProcessSemaphoreV2

zookeeper curator使用

Zookeeper应用场景之分布式屏障Barrier