Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.kiddcorp.zk;
- 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;
- /**
- *
- * @author jwkidd3
- *
- */
- public class ZooKeeperConnection {
- private ZooKeeper zoo;
- final CountDownLatch connectedSignal = new CountDownLatch(1);
- /*
- * Here CountDownLatch is used to stop (wait) the main process until the
- * client connects with the ZooKeeper ensemble.
- *
- * The ZooKeeper ensemble replies the connection status through the Watcher
- * callback. The Watcher callback will be called once the client connects
- * with the ZooKeeper ensemble and the Watcher callback calls the countDown
- * method of the CountDownLatch to release the lock, await in the main
- * process.
- */
- public ZooKeeper connect(String host) throws IOException, InterruptedException {
- zoo = new ZooKeeper(host, 5000, new Watcher() {
- public void process(WatchedEvent we) {
- if (we.getState() == KeeperState.SyncConnected) {
- connectedSignal.countDown();
- }
- }
- });
- connectedSignal.await();
- return zoo;
- }
- public void close() throws InterruptedException {
- zoo.close();
- }
- public static void main(String[] args) {
- ZooKeeper zk;
- ZooKeeperConnection conn;
- conn = new ZooKeeperConnection();
- try {
- zk = conn.connect("localhost:2183");
- System.out.println(zk.getSessionId());
- zk.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement