Zookeeper实例Curator API-使用Curator的异步接口

来源:互联网 发布:tensorflow可视化界面 编辑:程序博客网 时间:2024/04/30 12:07


import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.apache.curator.framework.CuratorFramework;import org.apache.curator.framework.CuratorFrameworkFactory;import org.apache.curator.framework.api.BackgroundCallback;import org.apache.curator.framework.api.CuratorEvent;import org.apache.curator.retry.ExponentialBackoffRetry;import org.apache.zookeeper.CreateMode;/** *  * @ClassName: Create_Node_Background_Sample * @Description: TODO(使用Curator的异步接口) * @author RongShu * @date 2017年6月17日 下午1:16:40 * */public class Create_Node_Background_Sample {static String path = "/zk-book";static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181").sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();static CountDownLatch semaphore = new CountDownLatch(2);static ExecutorService tp = Executors.newFixedThreadPool(2);public static void main(String[] args) throws Exception {client.start();System.out.println("Main thread: " + Thread.currentThread().getName());// 此处传入了自定义的Executorclient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]");System.out.println("Thread of processResult: " + Thread.currentThread().getName());semaphore.countDown();}}, tp).forPath(path, "init".getBytes());// 此处没有传入自定义的Executorclient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]");System.out.println("Thread of processResult: " + Thread.currentThread().getName());semaphore.countDown();}}).forPath(path, "init".getBytes());semaphore.await();tp.shutdown();}}输出Main thread: mainevent[code: -110, type: CREATE]Thread of processResult: main-EventThreadevent[code: 0, type: CREATE]Thread of processResult: pool-3-thread-1


参考

1.《从Paxos到Zookeeper:分布式一致性原理与实践》

2.https://zookeeper.apache.org/doc/r3.5.3-beta/javaExample.html

阅读全文
0 0
原创粉丝点击