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.
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:
(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.
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, ...