O'Reilly logo

ZooKeeper by Flavio Junqueira, Benjamin Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Getting Started with the ZooKeeper API

In Chapter 2, we used zkCli to introduce the basic ZooKeeper operations. In this chapter we are going to see how we actually use the API in applications. Here we give an introduction of how to program with the ZooKeeper API, showing how to create a session and implement a watcher. We also start coding our master–worker example.

Setting the ZooKeeper CLASSPATH

We need to set up the appropriate classpath to run and compile ZooKeeper Java code. ZooKeeper uses a number of third-party libraries in addition to the ZooKeeper JAR file. To make typing a little easier and to make the text a little more readable, we will use an environment variable CLASSPATH with all the required libraries. The script zkEnv.sh in the bin directory of the ZooKeeper distribution sets this environment variable for us. We need to source it using the following:

ZOOBINDIR="<path_to_distro>/bin"
. "$ZOOBINDIR"/zkEnv.sh

(On Windows, use the call command instead of the period and the zkEnv.cmd script.)

Once we run this script, the CLASSPATH variable will be set correctly. We will use it to compile and run our Java programs.

Creating a ZooKeeper Session

The ZooKeeper API is built around a ZooKeeper handle that is passed to every API call. This handle represents a session with ZooKeeper. As shown in Figure 3-1, a session that is established with one ZooKeeper server will migrate to another ZooKeeper server if its connection is broken. As long as the session is alive, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required