curator 簡潔監聽例子


ZooKeeper(3.4.5) 使用Curator監聽事件

 

package com.huey.dream.demo;
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.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode; import org.apache.curator.retry.ExponentialBackoffRetry; /** * Curator事件監聽 * @author huey * @version 1.0 * @created 2015-3-2 */ public class CarutorDemo {  public static void main(String[] args) throws Exception {   CuratorFramework client = CuratorFrameworkFactory.builder()    .connectString("192.168.1.109:2181")    .sessionTimeoutMs(5000)    .connectionTimeoutMs(3000)    .retryPolicy(new ExponentialBackoffRetry(1000, 3))    .build();   client.start();   client.create()    .creatingParentsIfNeeded()    .forPath("/zk-huey/cnode", "hello".getBytes());   /**   * 在注冊監聽器的時候,如果傳入此參數,當事件觸發時,邏輯由線程池處理   */   ExecutorService pool = Executors.newFixedThreadPool(2);   /**   * 監聽數據節點的變化情況   */   final NodeCache nodeCache = new NodeCache(client, "/zk-huey/cnode", false);   nodeCache.start(true);   nodeCache.getListenable().addListener(    new NodeCacheListener() {     @Override     public void nodeChanged() throws Exception {      System.out.println("Node data is changed, new data: " +       new String(nodeCache.getCurrentData().getData()));     }    },    pool   );   /**   * 監聽子節點的變化情況   */   final PathChildrenCache childrenCache = new PathChildrenCache(client, "/zk-huey", true);   childrenCache.start(StartMode.POST_INITIALIZED_EVENT);   childrenCache.getListenable().addListener(    new PathChildrenCacheListener() {     @Override     public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)       throws Exception {       switch (event.getType()) {       case CHILD_ADDED:        System.out.println("CHILD_ADDED: " + event.getData().getPath());        break;       case CHILD_REMOVED:        System.out.println("CHILD_REMOVED: " + event.getData().getPath());        break;       case CHILD_UPDATED:        System.out.println("CHILD_UPDATED: " + event.getData().getPath());        break;       default:        break;      }     }    },    pool   );   client.setData().forPath("/zk-huey/cnode", "world".getBytes());   Thread.sleep(10 * 1000);   pool.shutdown();   client.close();  } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM