-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathZooKeeperConnection.java
37 lines (31 loc) · 1.01 KB
/
ZooKeeperConnection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package demo;
import java.io.IOException;
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;
/**
* https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
*/
public class ZooKeeperConnection {
private ZooKeeper zoo;
final CountDownLatch connectedSignal = new CountDownLatch(1);
public ZooKeeper connect(String host) throws IOException, InterruptedException {
zoo = new ZooKeeper(host, 5000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
});
connectedSignal.await();
return zoo;
}
public void close() throws InterruptedException {
if (zoo != null) {
zoo.close();
}
}
}