1.首选以最简单的API为例。
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
其中,connectString表示要连接的zookeeper服务器地址列表,格式为:192.168.0.1:2181。支持多个地址拼接,中间用逗号分隔。其中地址后面还可以拼接上zookeeper的操作路径,比如:192.168.0.1:2181/zk/test。
sessionTimeout:会话超时时间,单位“毫秒”。通过心跳来监测会话的有效性。
watcher:监听节点的状态变化,如果发生变化则通知此watcher,做出相应处理。如果不需要监听,则可设置为null
其他接口
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
boolean canBeReadOnly)
此方法多了一个canBeReadOnly参数,此参数表示当前会话是否支持“只读”模式。
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
long sessionId, byte[] sessionPasswd)
此方法允许传入sessionId和sessionPasswd,目的是为了重复使用会话。通过以下方法获得:
zooKeeper.getSessionId();
zooKeeper.getSessionPasswd()
然后作为参数创建新的连接。当sessionId和sessionPasswd不正确时,服务器会返回Expired事件。