Created
January 8, 2019 13:09
-
-
Save geowarin/c5bf8b0e6b96cdb78b2246bf0b1455a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fds.zookeeper.toto; | |
import org.apache.zookeeper.KeeperException; | |
import org.apache.zookeeper.WatchedEvent; | |
import org.apache.zookeeper.Watcher; | |
import org.apache.zookeeper.ZooKeeper; | |
import java.io.IOException; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.function.Consumer; | |
import static java.lang.Thread.currentThread; | |
public class Main { | |
private static final String HOST = "localhost"; | |
private static final String WATCHED_PATH = "/toto"; | |
public static void main(String[] args) throws IOException, InterruptedException { | |
ZooKeeper zooKeeper = connect(HOST); | |
watchForever(zooKeeper, WATCHED_PATH, System.out::println); | |
currentThread().join(); | |
} | |
private static void watchForever(ZooKeeper zooKeeper, String path, Consumer<WatchedEvent> watcher) { | |
try { | |
zooKeeper.exists(path, event -> { | |
watchForever(zooKeeper, path, watcher); | |
watcher.accept(event); | |
}); | |
} catch (KeeperException | InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private static ZooKeeper connect(String host) throws IOException, InterruptedException { | |
CountDownLatch connectionLatch = new CountDownLatch(1); | |
ZooKeeper zoo = new ZooKeeper(host, 2000, event -> { | |
System.out.println(event); | |
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { | |
connectionLatch.countDown(); | |
} | |
}); | |
connectionLatch.await(); | |
return zoo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment