Zookeeper learning (5): java connection zookeeper

Keywords: Big Data Zookeeper Junit github Java

Before adding the connected Semaphore semaphore:

It has been reported that the connection failed, many posts on the Internet said that the firewall of the server where zookeeper is located is not closed, or the jdk version is inconsistent, and so on.

My own analysis of the feeling is as follows:

Although I've put ZooKeeper's initialization in the @Before tag, there's still a problem: "If it takes 5 seconds to complete code execution, but 10 seconds to connect zookeeper, then zookeeper hasn't succeeded yet, and the testCreate method in @Test has already started to execute, so code error will occur.“

The following code:

package com.qianliu.bigdata.zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class sampleZkClient {
    private static final String connectString = "192.168.48.132:2181,192.168.48.134:2181,192.168.48.135:2181";
    private static final int sessionTimeout = 2000;

    /** A semaphore, blocking program execution, used to wait for the zookeeper connection to succeed and send a successful signal. */
    /*Once unlocked, because it takes 10 seconds to connect to zookeeper and 5 seconds to execute the program, the program runs to write data to the zookeeper node.
    ,zookeeper There is no connection yet, so the program will report an error.
    */
    static final CountDownLatch connectedSemaphore = new CountDownLatch(1);
    ZooKeeper zkClient = null;

    @Before
    public void testInit() throws Exception{
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // Get the state of the event
                Event.KeeperState keeperState = event.getState();
                Event.EventType eventType = event.getType();
                // If a connection is established
                if (Event.KeeperState.SyncConnected == keeperState) {
                    if (Event.EventType.None == eventType) {
                        // If the connection is successful, the semaphore is sent to allow subsequent blockers to execute downward.
                        System.out.println("zk Establish connection");
                        connectedSemaphore.countDown();
                    }
                }
            }
        });

        // Blocking
        connectedSemaphore.await();
        System.out.println("..");
    }
    /**
     * Addition, deletion and modification of data
     *
     * @throws InterruptedException
     * @throws KeeperException
     */

    // Create data nodes into zk
    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        // PARAMETER 1: PATH PARAMETER 2: NODE LARGE DATA PARAMETER 3: NODE'S PRIvilege PARAMETER 4: NODE TYPE
        String nodeCreated = zkClient.create("/eclipse4", "hellozk4".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //Uploaded data can be of any type, but must be converted to byte []
        System.err.println(nodeCreated);

    }

    // Get child nodes
    @Test
    public void getChildren() throws Exception {
        List<String> children = zkClient.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        Thread.sleep(Long.MAX_VALUE);
        zkClient.close();
    }

    @After
    public void closeZkConnection() throws Exception{
        zkClient.close();
    }
}

Attach github source code: https://github.com/LUK-qianliu/zookeeperConnection

Posted by bravo81 on Sat, 02 Feb 2019 13:09:16 -0800