官网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