import java.util.List; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class MyTest { @Autowired ZKManager zKManager; @Test public void test() { try { String path = "/famliy"; byte[] data = "Famliy.Lee".getBytes(); //zKManager.zk.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zKManager.zk.create(path+"/thomas", "thomas".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); zKManager.zk.create(path+"/ellen", "ellen".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); zKManager.zk.delete(path+"/thomas", -1); } catch (Exception e) { e.printStackTrace(); } } }
import java.io.IOException; import java.util.List; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; public class ZKManager implements Watcher { private String hostPort="127.0.0.1:2181"; private int timeOut=20000; private String path="/famliy"; public ZooKeeper zk; public ZKManager() throws IOException{ zk = new ZooKeeper(hostPort,timeOut,this); } public void process(WatchedEvent event) { System.out.println("/test is change: type="+event.getType()+" | state="+event.getState()); try { List<String> zNodes=zk.getChildren(path, this); if(null!=zNodes){ for(String zNode : zNodes){ System.out.println("zNode="+zNode); } } } catch (Exception e) { e.printStackTrace(); } } }
执行结果:
/test is change: type=None | state=SyncConnected
zNode=thomas
/test is change: type=NodeChildrenChanged | state=SyncConnected
zNode=ellen
zNode=thomas
/test is change: type=NodeChildrenChanged | state=SyncConnected
zNode=ellen
ZKManager 负责创建zookeeper链接。
注:
getChildren getData监控变化,不过只能使用一次 。如果想持续监控的话每次都重新调用这些方法。
zk.getChildren(path, this );监控子目录的变化,this是一个Watcher(在这里时ZKManager),这样当zookeeper相关路径下的东西改变后就会调用ZKManager的process方法来通知client。
getChildren("/family",this ) ZKManager负责watch family 下子节点的状态,当有变化时调用自己的process方法
getData("/family",this)ZKManager负责watch family自己数据的状态,有变化时调用自己的process方法