Java操作ZooKeeper

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 children = zkClient.getChildren("/", true) ;
        Iterator iter = children.iterator() ;
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }
        zkClient.close(); // 關閉客戶端連接,前提:你沒有啟用監聽
    }
}

這個時候就可以取得全部的節點的列表,相當於“ls /”作用。

發佈留言