Curator API使用

壹頁書發表於2016-05-10
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(10003));  
  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(31000));  
  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.     }  



參考:

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2097459/,如需轉載,請註明出處,否則將追究法律責任。

相關文章