简介
curator针对分布式场景实现了分布式屏障:barrier。我们在分布式系统中可以使用barrier去阻塞进程,知道某个条件被触发。其实跟Java多线程的barrier是一样的。
例如:当两个进程在执行任务的时候,A调用了B,A需要等待B完成以后的通知
官方文档:http://curator.apache.org/curator-recipes/barrier.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
主线程等待屏障被移除了以后继续执行