Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. package com.kiddcorp.zk;
  2.  
  3. import java.io.IOException;
  4. import java.util.concurrent.CountDownLatch;
  5.  
  6. import org.apache.zookeeper.WatchedEvent;
  7. import org.apache.zookeeper.Watcher;
  8. import org.apache.zookeeper.Watcher.Event.KeeperState;
  9. import org.apache.zookeeper.ZooKeeper;
  10.  
  11. /**
  12. *
  13. * @author jwkidd3
  14. *
  15. */
  16. public class ZooKeeperConnection {
  17.  
  18. private ZooKeeper zoo;
  19. final CountDownLatch connectedSignal = new CountDownLatch(1);
  20.  
  21. /*
  22. * Here CountDownLatch is used to stop (wait) the main process until the
  23. * client connects with the ZooKeeper ensemble.
  24. *
  25. * The ZooKeeper ensemble replies the connection status through the Watcher
  26. * callback. The Watcher callback will be called once the client connects
  27. * with the ZooKeeper ensemble and the Watcher callback calls the countDown
  28. * method of the CountDownLatch to release the lock, await in the main
  29. * process.
  30. */
  31. public ZooKeeper connect(String host) throws IOException, InterruptedException {
  32.  
  33. zoo = new ZooKeeper(host, 5000, new Watcher() {
  34.  
  35. public void process(WatchedEvent we) {
  36.  
  37. if (we.getState() == KeeperState.SyncConnected) {
  38. connectedSignal.countDown();
  39. }
  40. }
  41. });
  42.  
  43. connectedSignal.await();
  44. return zoo;
  45. }
  46.  
  47. public void close() throws InterruptedException {
  48. zoo.close();
  49. }
  50.  
  51. public static void main(String[] args) {
  52. ZooKeeper zk;
  53. ZooKeeperConnection conn;
  54.  
  55. conn = new ZooKeeperConnection();
  56. try {
  57. zk = conn.connect("localhost:2183");
  58. System.out.println(zk.getSessionId());
  59. zk.close();
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement