[ Tutorial ] Maven – Connect to a ZooKeeper in Java

This tutorial will cover how to connect to ZooKeeper in Java with Maven project.

(Click here to download the source code for this tutorial)

1. What is Apache Maven?

Apache Maven (or just Maven) is simply “a software project management and comprehension tool.” (from http://maven.apache.org)  In this case, Maven is designed to help you with downloading what’s called dependency – think of them as the external JAR files you need to explicitly download and include them in your build path.

1.1. Create Maven Project

Maven utilizes POM (Project Object Model); this is what makes Maven very useful.  You specify the required dependencies here, and after updating the project, it will automatically download the dependencies for you.

First step is to create a Maven project.  (How to create Maven project). Under the maven project you just created, you will see an xml file called pom.xml.

1.2. Configure Project

Image

Open that, and edit it as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>zook</groupId>
    <artifactId>zook</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <name>zook</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
        </dependency>
    </dependencies>
</project>

Right click on your project > Maven > Update Project (or Alt + F5).  This usually works for me if “Force Update of Snapshots/Releases” is checked.

Image

Then click OK.

This enables you to use any classes included in that zookeeper dependency.

2. Connect to ZooKeeper

2.1. ZooKeeper Connector Class

Next step is to create a new class, let’s call it ZkConnector.

Here, you are going to import 6 following classes:

import java.io.IOException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

ZkConnector class is for your program to interact with ZooKeeper server.  We will declare two global variables here:

ZooKeeper zookeeper;
java.util.concurrent.CountDownLatch connectedSignal = new java.util.concurrent.CountDownLatch(1);

and write three different methods.  First method connects to the ZooKeeper server by passing a hosts argument.  Another method tells ZooKeeper server to shut down, and the third method gets the instance of live ZooKeeper server.

2.2. Connect method

public void connect(String host) throws IOException, InterruptedException {
    zookeeper = new ZooKeeper(host, 5000, 
                              new Watcher() {
                                  public void process(WatchedEvent event) {
                                      if (event.getState() == KeeperState.SyncConnected) {
                                          connectedSignal.countDown();
                                      }
                                  }
                              });
                              connectedSignal.await();
}

2.3. Close method

public void close() throws InterruptedException {
    zookeeper.close();
}

2.4. Getter method:

public ZooKeeper getZooKeeper() {
    if (zookeeper == null || !zookeeper.getState().equals(States.CONNECTED)) {
        throw new IllegalStateException("ZooKeeper is not connected.");
    }
    return zookeeper;
}

3. Test ZooKeeper Connection

3.1. Tester Class

Let’s test this class to see if it works.

We’re going to create another class, call it ZkConnectTest. This class will import 5 classes as follows:

import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

Many methods in the zookeeper API throw exceptions.  We need to add a throws declaration to the main method of three exceptions: IOException, InterruptedException, KeeperException.  Another way is to enclose the exception throwing statements with try... catch, but we’ll make our main method throw those exceptions.

First, let’s declare a new ZooKeeper variable, call it zk.

ZooKeeper zk;

Next, create a new instance of the ZkConnector class, let’s call it zkc.

ZkConnector zkc = new ZkConnector();

In the last 3 lines, we are going to:

  • connect to the zookeeper
  • let zk be the instance of the zookeeper connected
  • and create a new znode, just to see if it worked correctly.
zkc.connect("localhost");
zk = zkc.getZooKeeper();
zk.create("/newznode", "new znode".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

3.2. Run an Instance of ZooKeeper

Save your source code and let’s create the ZooKeeper instance.  We need to have an instance of ZooKeeper running in order for your program to work. Open up a command prompt (if you’re using windows), or a terminal (Mac or Linux users) and type in the following command:

Windows users: zkServer.cmd
Mac/Linux users:  ./zkServer.sh -start

3.3. Interact With ZooKeeper as Client

Next, we are going to connect to the zookeeper as a client.  Open up another command prompt (windows) or a terminal (Mac or Linux) and type in the following command:

Windows users: zkCli.cmd
Mac/Linux users: ./zkCli.sh -server:2181

In the client window, type in the following command: ls /

If you have not created any znodes yet, you should only get zookeeper znode.  This is implemented in the zookeeper by default, and it cannot be destroyed.  What we just did was print a list of all children znodes of the root (/) znode.

Go back to the program we wrote, and run it.

Then go back to the client window, and type in the ls / command.  If you see the newznode, then we successfully wrote a program to connect to the zookeeper. Thanks for reading, and happy zookeeping.

(Click here to download the source code for this tutorial)

Advertisements

One thought on “[ Tutorial ] Maven – Connect to a ZooKeeper in Java

  1. Pingback: ZNode Types and How to Create, Read, Delete, and Write in ZooKeeper (via zkClient) | Inki Hong's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s