ZooKeeper (3.4.5) using curator to listen for events
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 Event Monitoring *@author Huey *@version 1.0 *@created 2015-3-2 */PublicClass Carutordemo { PublicStaticvoid 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 ()); /** * When registering the listener, if this parameter is passed in, the logic is handled by the thread pool when the event is triggered */ Executorservice pool = Executors.newfixedthreadpool (2); /** * Monitor the change of data node */ Final Nodecache Nodecache =New Nodecache (Client,"/zk-huey/cnode",FALSE); Nodecache.start (true); Nodecache.getlistenable (). AddListener ( New Nodecachelistener () { @Override Publicvoid NodeChanged ()Throws Exception { System.out.println ("Node data is changed, new data:" + New String (Nodecache.getcurrentdata (). GetData ())); } }, Pool ); /** * Monitor the change of child nodes */ Final Pathchildrencache Childrencache =New Pathchildrencache (Client,"/zk-huey",true); Childrencache.start (startmode.post_initialized_event); Childrencache.getlistenable (). AddListener ( New Pathchildrencachelistener () { @Override Publicvoid 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); Span class= "indent" > Pool.shutdown (); Client.close (); } /span>
Curator Simple Listener example