1、开发环境配置: 添加ZooKeeper中的zookeeper-3.4.9.jar, lib的支持库文件 2、连接ZooKeeper服务器集群使用“org.apache.zookeeper.ZooKeeper”这个类完成,而后在这个类中定义有如下一个构造方法:public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher) throws IOException; |- “String connectString”:定义要连接的ZooKeeper服务器的主机,如果有多台主机使用“,”分割; |- “int sessionTimeout”:连接的超时时间; |- “Watcher watcher”:定义监听程序;
public class ZooKeeperConnect { private static final String CONNECT_HOSTS = "ZooKeeper主机IP,ZooKeeper主机IP....(,隔开):2181" ; public static void main(String[] args) throws Exception { ZooKeeper zkClient = new ZooKeeper(CONNECT_HOSTS, 2000, new Watcher(){ @Override public void process(WatchedEvent event) { // 此处的方法体暂时为空 }}) ; System.out.println(zkClient); } }在ZooKeeper 里面最为重要的部分就是节点的信息,所以也可以利用ZooKeeper 类的对象取得所有的节点信息: · 方法:public List getChildren(String path, boolean watch) throws KeeperException,InterruptedException;
public class ZooKeeperNode { private static final String CONNECT_HOSTS = "ZooKeeper主机IP,ZooKeeper主机IP....(,隔开):2181" ; public static void main(String[] args) throws Exception { ZooKeeper zkClient = new ZooKeeper(CONNECT_HOSTS, 2000, new Watcher(){ @Override public void process(WatchedEvent event) { // 此处的方法体暂时为空 }}) ; List<String> children = zkClient.getChildren("/", true) ; Iterator<String> iter = children.iterator() ; while (iter.hasNext()) { System.out.println(iter.next()); } zkClient.close(); // 关闭客户端连接,前提:你没有启用监听 } }这个时候就可以取得全部的节点的列表,相当于“ls /”作用。