如何调用Java API来创建一个最基本的Zookerper ,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
下面介绍如何调用 Java API来创建一个最基本的 Zookerper 会话实例
代码清单
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
public class zookeeper_simple_usage implements Watcher {
private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
public static void main (String[] args) throws Exception{
ZooKeeper zookeeper = new ZooKeeper("202.201.13.55:2100",
5000,
new zookeeper_simple_usage());
System.out.println(zookeeper.getState());
try{
connectedSemaphore.await();
}
catch (InterruptedException e){}
System.out.println("ZooKeeper session established.");
}
public void process(WatchedEvent event) {
System.out.println("Received watched evnet: " + event);
if (KeeperState.SyncConnected == event.getState()) {
connectedSemaphore.countDown();
}
}
}
必须重载 WatchedEvent
中的 process
方法。
执行结果
Received watched evnet: WatchedEvent state:SyncConnected type:None path:null
ZooKeeper session established.
依赖包
需要在Build Path中添加四个包
zookerper-3.4.6.jar
log4j-1.2.14.jar
slf4j-api-1.7.12.jar
slf4j-simple-1.7.12.jar
不然会报找不到类的错误。
关于如何调用Java API来创建一个最基本的Zookerper 问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注天达云行业资讯频道了解更多相关知识。