官網API
http://zookeeper.apache.org/doc/r3.4.6/api/index.html
JAR包
\zookeeper-3.3.6\lib\
jline-0.9.94.jar
\zookeeper-3.3.6\lib\
log4j-1.2.15.jar
\zookeeper-3.3.6\
zookeeper-3.3.6.jar
Demo代碼
注意代碼中的注解
package hello.zookeeper.api;import java.util.List;import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.junit.Before;
import org.junit.Test;
import org.apache.zookeeper.ZooKeeper;public class ZkClient {/** 此處必須與zookeeper的zoo.cfg中一樣* zk會選擇一個連接* 如果windows上運行,hosts也要配置一致*/private static final String connString="zk1:2181,zk2:2181,zk3:2181";/** 超時:連接超時,同步時間間隔,zk有節點值變更,在這個時間內同步*/private static final int sessionTimeout=2000;private ZooKeeper zk=null;@Beforepublic void init() throws Exception{zk=new ZooKeeper(connString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {System.out.println("監聽器:"+event.getType()+"-"+event.getPath());}});}@Testpublic void create() throws Exception{String path="/eclipse";if(zk.exists(path, false)==null){String msg=zk.create(path, "helloworld".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("create:"+msg);}else{System.out.println(path+"已存在!");}}@Testpublic void getChildren() throws Exception{List<String> children = zk.getChildren("/", true);if(children!=null&&children.size()>0){System.out.println("子目錄如下:");for(String s:children){System.out.println(s);}}}@Testpublic void setData() throws Exception{//-1表示刪除所有版本zk.setData("/eclipse", "hello earth !".getBytes(), -1);getData();}@Testpublic void getData() throws Exception{byte[] data = zk.getData("/eclipse", true, null);System.out.println("getData():"+new String(data));}@Testpublic void deleteZnode() throws Exception{zk.delete("/eclipse", -1);getChildren();}}
-------------
更多的Java,Angular,Android,大數據,J2EE,Python,數據庫,Linux,Java架構師,:
http://www.cnblogs.com/zengmiaogen/p/7083694.html