java客户端测试连接zookeeper服务器

时间:2022-01-23 08:26:22

连接下zookeeper服务器,判断是否连接成功。


下面有些额外代码,是因为不加上的话会报错,错误日志是:

Exception in thread "main" org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /

网上很多都说是linux服务器没关闭防火墙,但我关闭了防火墙还是照样报错。


public class SimpleZkClient {

public static void waitUntilConnected(ZooKeeper testZooKeeper, CountDownLatch testLatch) {
if(testZooKeeper.getState() == States.CONNECTING) {
try {
testLatch.await();
} catch (InterruptedException err) {
System.out.println("Latch exception");
}
}
}

static class ConnectedWatcher implements Watcher {
private CountDownLatch connectedLatch;
ConnectedWatcher(CountDownLatch connectedLatch) {
this.connectedLatch = connectedLatch; /* CountDownLatch实例初始化时设为1即可 */
}

/**
* zookeeper服务集群监听到某个指定数据节点上发生的事件后,会通知监听注册者(客户端),
* 然后客户端就会调用process方法,并将接收到的事件event作为参数传递给process方法
*/
@Override
public void process(WatchedEvent event) {
if (event.getState() == KeeperState.SyncConnected) {
connectedLatch.countDown(); /* ZK连接成功时,计数器由1减为0 */
}
System.out.println("节点:" + event.getPath() + " 发生了事件:" + event.getType());
}
}

public static void main(String[] args) throws Exception {
CountDownLatch sampleLatch = new CountDownLatch(1);
Watcher sampleWatcher = new ConnectedWatcher (sampleLatch);

/*
* 创建一个zookeeper的java客户端
* 三个参数分别是:
* connectString :zk服务器地址
* sessionTimeout:连接超时阈值
* watcher:监听器
*/
ZooKeeper zkCli = new ZooKeeper("192.168.77.70:2181,192.168.77.80:2181", 2000, sampleWatcher);

/* 只有当zkCli链接成功(状态为 SyncConnected)时,此函数调用才结束 */
waitUntilConnected(zkCli, sampleLatch);
/*接下来就可以继续zkCli访问了,避免因为zkCli未连接成功时的访问出错 */

// 获取"/"节点下的子节点列表,并对"/"节点注册监听器
List<String> children = zkCli.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
zkCli.close();
}
}

结果:

java客户端测试连接zookeeper服务器