ITPub博客

首页 > 应用开发 > Java > Curator API使用

Curator API使用

原创 Java 作者:壹頁書 时间:2016-05-10 22:15:56 0 删除 编辑
Curator 是操作ZooKeeper的开源客户端.
类似于JDBC什么的吧.
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>2.4.2</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.4.2</version>
</dependency>



同步接口
1.创建节点
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     client.create().forPath("/t1", "t1".getBytes());  
  4.     client.create().withMode(CreateMode.EPHEMERAL).forPath("/e1","e1".getBytes());  
  5.     client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/p1/p2/p3","p1".getBytes());  
  6.       
  7.     client.close();  
  8. }  
  9.   
  10. public static CuratorFramework getConnection() {  
  11.     CuratorFramework client;  
  12.     client = CuratorFrameworkFactory.newClient("172.16.1.78:2181", new ExponentialBackoffRetry(1000, 3));  
  13.     client.start();  
  14.     return client;  
  15. }  

节点类型一共有四种
CreateMode.EPHEMERAL 临时节点
CreateMode.EPHEMERAL_SEQUENTIAL 临时顺序节点
CreateMode.PERSISTENT 持久节点
CreateMode.PERSISTENT_SEQUENTIAL 持久顺序节点

2.删除节点
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     //递归删除子节点  
  4.     client.delete().deletingChildrenIfNeeded().forPath("/p1");  
  5.       
  6.     //强制保证删除  
  7.     client.delete().guaranteed().forPath("/t1");  
  8.     client.close();  
  9. }  


3.读取节点数据
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     byte[] data=client.getData().forPath("/t");  
  4.     System.out.println(new String(data));  
  5. }  


4.更新节点数据
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     client.setData().forPath("/t","Hello World".getBytes());  
  4.     client.close();  
  5. }  


异步接口

1.异步接口调用BackgroundCallback回调函数
  1. public static void main(String[] args) throws Exception {  
  2.         final CountDownLatch latch = new CountDownLatch(1);  
  3.         ExecutorService threadpool = Executors.newFixedThreadPool(5);  
  4.         BackgroundCallback callback = new BackgroundCallback() {  
  5.   
  6.             public void processResult(CuratorFramework arg0, CuratorEvent event) throws Exception {  
  7.                 System.out.println(event.getType().name());  
  8.                 System.out.println("EventCode:" + event.getResultCode());  
  9.                 System.out.println(Thread.currentThread().getName());  
  10.                 latch.countDown();  
  11.             }  
  12.         };  
  13.         CuratorFramework client = getConnection();  
  14.         client.delete().inBackground(callback, threadpool).forPath("/t");  
  15.   
  16.         latch.await();  
  17.         threadpool.shutdown();  
  18.         client.close();  
  19.     }  

结果:
DELETE
EventCode:-101
pool-1-thread-1

2.事件监听

监听节点数据变化.
监听的节点可以不存在,但是一旦创建也会触发事件.
删除监听的节点,不会触发事件.
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     final NodeCache cache = new NodeCache(client, "/t");  
  4.     cache.start(true);  
  5.     cache.getListenable().addListener(new NodeCacheListener() {  
  6.   
  7.         public void nodeChanged() throws Exception {  
  8.             byte[] data = cache.getCurrentData().getData();  
  9.             System.out.println(new String(data));  
  10.         }  
  11.     });  
  12.     Thread.sleep(Integer.MAX_VALUE);  
  13. }  

监听子节点变化
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     final PathChildrenCache cache = new PathChildrenCache(client, "/t", true);  
  4.     cache.start(StartMode.POST_INITIALIZED_EVENT);  
  5.     cache.getListenable().addListener(new PathChildrenCacheListener() {  
  6.   
  7.         public void childEvent(CuratorFramework arg0, PathChildrenCacheEvent event) throws Exception {  
  8.             System.out.println(event.getType().name());  
  9.             System.out.println(event.getData().getPath());  
  10.   
  11.         }  
  12.     });  
  13.     Thread.sleep(Integer.MAX_VALUE);  
  14. }  

子节点变化包括
event.getType()
CHILD_ADDED 子节点创建
CHILD_UPDATED 子节点数据变更
CHILD_REMOVED 子节点删除

3.Master选举
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     LeaderSelector selector=new LeaderSelector(client,"/master",new LeaderSelectorListenerAdapter() {  
  4.           
  5.         public void takeLeadership(CuratorFramework client) throws Exception {  
  6.             System.out.println("成为Master角色");  
  7.             Thread.sleep(1000);  
  8.             System.out.println("释放");  
  9.         }  
  10.     });  
  11.     selector.autoRequeue();  
  12.     selector.start();  
  13.     Thread.sleep(Integer.MAX_VALUE);  
  14. }  

4.分布式锁
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.       
  4.     final InterProcessMutex lock = new InterProcessMutex(client, "/lock");  
  5.     final CountDownLatch latch = new CountDownLatch(1);  
  6.     for (int i = 0; i < 30; i++) {  
  7.         new Thread(new Runnable() {  
  8.             public void run() {  
  9.                 try {  
  10.                     latch.await();  
  11.                     lock.acquire();  
  12.                   
  13.                     System.out.println(new Date());  
  14.                     Thread.sleep(1000);  
  15.                 } catch (InterruptedException e) {  
  16.                     e.printStackTrace();  
  17.                 } catch (Exception e) {  
  18.                     e.printStackTrace();  
  19.                 } finally {  
  20.                     try {  
  21.                         lock.release();  
  22.                     } catch (Exception e) {  
  23.                         // TODO Auto-generated catch block  
  24.                         e.printStackTrace();  
  25.                     }  
  26.                 }  
  27.             }  
  28.         }).start();  
  29.     }  
  30.     latch.countDown();  
  31. }  

5.分布式计数器
  1. public static void main(String[] args) throws Exception {  
  2.     CuratorFramework client = getConnection();  
  3.     DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, "/atomicInteger",  
  4.             new RetryNTimes(3, 1000));  
  5.     AtomicValue<Integer> rc = atomicInteger.add(8);  
  6.   
  7.     System.out.println(rc.succeeded());  
  8.     System.out.println(rc.postValue());  
  9. }  


6.分布式Barrier
  1. public static void main(String[] args) throws Exception {  
  2.         final CountDownLatch latch = new CountDownLatch(30);  
  3.         for (int i = 0; i < 30; i++) {  
  4.             new Thread(new Runnable() {  
  5.   
  6.                 public void run() {  
  7.                     try {  
  8.                         CuratorFramework client = getConnection();  
  9.                         DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");  
  10.                         barrier.setBarrier();  
  11.                         System.out.println(Thread.currentThread().getName() + ",waiting..");  
  12.                         latch.countDown();  
  13.                         barrier.waitOnBarrier();  
  14.                         System.out.println(Thread.currentThread().getName() + ",start!!");  
  15.                         client.close();  
  16.                     } catch (Exception e) {  
  17.                         // TODO Auto-generated catch block  
  18.                         e.printStackTrace();  
  19.                     }  
  20.                 }  
  21.             }).start();  
  22.         }  
  23.         latch.await();  
  24.         CuratorFramework client = getConnection();  
  25.         DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");  
  26.         barrier.removeBarrier();  
  27.         client.close();  
  28.     }  



参考:
http://ifeve.com/zookeeper-path-cache/

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2097459/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339946