1、DataPublisher.java
package com.neohope.zookeeper.test; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import java.io.IOException; /** * Created by Hansen */ public class DataPublisher { public void publishTest(String hostPort,String znode) throws IOException, KeeperException, InterruptedException { ZooKeeper zk = new ZooKeeper("localhost:2181", 30000, new Watcher() { public void process(WatchedEvent event) { //do nothing }}); //删掉节点 Stat stat =zk.exists(znode, false); if(stat!=null) { zk.delete(znode, -1); } //开始测试 zk.create(znode,"test01".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); byte[] buff =zk.getData(znode, false, null); System.out.println("data is " + new String(buff,"UTF-8")); zk.setData(znode,"test02".getBytes(), -1); buff = zk.getData(znode, false, null); System.out.println("data is " + new String(buff,"UTF-8")); zk.delete(znode, -1); zk.close(); } public static void main(String[] args) throws IOException, KeeperException, InterruptedException { String hostPort = "localhost:2181"; String znode = "/neohope/test"; DataPublisher publisher = new DataPublisher(); publisher.publishTest(hostPort,znode); } }
2、与Zookeeper Watcher配合使用,试一下。