Zookeeper

zkCli.sh命令:

stat命令可以得到一个znode节点的属性,并允许我们在已经存在的znode节点上设置监视点。通过在路径后面设置参数true(这个参数在ls命令中也可以使用)来添加监视点

ZooKeeper的API

创建ZooKeeper句柄的构造函数 ZooKeeper(String connectString,int sessionTimeout,Watcher watcher);

其中:
connectString:包含主机名和ZooKeeper服务器的端口。我们之前通过zkCli连接ZooKeeper服务时,已经列出过这些服务器。
sessionTimeout:以毫秒为单位,表示ZooKeeper等待客户端通信的最长时间,之后会声明会话已死亡,ZooKeeper会话一般设置超时时间为5~10秒。
watcher:用于接收会话事件的一个对象,这个对象需要我们自己创建。因为Wacher定义为接口,所以我们需要自己实现一个类,然后初始化这个类的实例并传入ZooKeeper的构造函数中。客户端使用Watcher接口来监控与ZooKeeper之间会话的健康情况。与ZooKeeper服务器之间建立或失去连接时就会产生事件。它们同样还能用于监控ZooKeeper数据的变化。最终,如果与ZooKeeper的会话过期,也会通过Watcher接口传递事件来通知客户端的应用。

简单示例:

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher;
public class Master implements Watcher {
    ZooKeeper zk;
    String hostPort;
    Master(String hostPort) {
        this.hostPort = hostPort;
    }
    void startZK() {
        zk = new ZooKeeper(hostPort, 15000, this);
    }
    public void process(WatchedEvent e) {
        System.out.println(e);
    }
    public static void main(String args[]) throws Exception {
        Master m = new Master(args[0]);
        m.startZK();
        // wait for a bit
        Thread.sleep(60000);
    }
}       

  

posted @ 2019-05-06 11:51  jqbai  阅读(140)  评论(0编辑  收藏  举报