The Apache Curator API is pretty slick. It is written in a “fluent” style making it nice and readable. Also the use of “anonymous functions” aka lamdas make it fun to work with.
Let’s examine the PathChildrenCache class. A PathChildrenCache is a construct that does local mirroring of a ZooKeeper path. We can set up an “event handler” for the cache, which will be called when an event takes place on a watched zNode. There’s an ENUM which contains all possible events, and our event handler will match on the type of event. Holy crap I’m having JavaScript flash backs here…
requirements:
The basic setup:
Now we add a “callback” in the form of a PathChildrenCacheListener (and a helper just to print stuff out for now).
To use the PathChildrenCacheListener interface we need to implement a childEvent method:
Now just add some basic driver code and watch the output to see the PathChildrenCacheListener in action!
Why all the Thread.sleep’s? Good question. These Curator methods all seem to run as background processes, meaning that synchronous execution cannot be guaranteed. It is even more confusing to me as the SyncBuilder part of the library is “always in the background” which is the opposite of how other frameworks like Node.js implements sync. More research will be needed.