六、curator recipes之屏障barrier
阿新 • • 發佈:2019-01-14
close exceptio exce 進程 需要 framework eba arr pes
簡介
當兩個進程在執行任務的時候,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)); privatestatic 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