Author: Walking Sahara in the Rain Source: https://liudongdong.top Official Account: Walking Sahara in the Rain Remarks: Welcome to pay attention to the public account, learn technology, grow up together!

Bonus at the end of the article: hundreds of e-books, waiting for you to receive ^ V ^

Environmental Description:

  1. The server is a Centos7 cluster
  2. ZK is version 3.4.10.tar.gz of ZooKeeper
  3. The JDK 1.8

First, create the project

1. Add dependency packages. The POM file is as follows

<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> The < version > 2.8.2 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/org.apache.zookeeper/zook eeper --> <dependency> < the groupId > org. Apache. Zookeeper < / groupId > < artifactId > zookeeper < / artifactId > < version > 3.4.10 < / version > < / dependency > </dependencies>

2. Configure log files

The resource file creates the log configuration file log4j.properties

log4j.rootLogger=INFO, stdout 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n 
log4j.appender.logfile=org.apache.log4j.FileAppender 
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

Two, the code to achieve the ZK command

0. Create a connection

Connecting to the cluster IP and external port 2181, the cluster map has been configured in Windows.

The code implements the connection:

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Test
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

Run the print result

image.png

2. Create nodes

Create a /idea node of type temporary

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Before
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

@Test
public void createTest() throws Exception{
    String s = zkClient.create("/idea", "helloworld".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    System.out.println(s);
}

Print the result

image.png

3. Monitor node changes

Monitor the changes of child nodes under the root node

private static final String IPS = "master:2181,slave1:2181,slave2:2181"; private static final int SESSIONTIMEOUT = 200; private ZooKeeper zkClient = null; @Before public void contectTest() throws Exception{ zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { System.out.println(event.getType() + "--" + event.getPath()); try { zkClient.getChildren("/", true); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }}}); System.out.println("=================="); System.out.println(zkClient.getState()); System.out.println("=================="); } @Test public void childrenTest() throws Exception{ List<String> children = zkClient.getChildren("/", true); for (String ch : children){ System.out.println(ch); } Thread.sleep(Long.MAX_VALUE); }

Add nodes in the Xshell model, and you can imitate adding nodes in your code

[zk: localhost:2181(CONNECTED) 0] create -e /java "java"
Created /java
[zk: localhost:2181(CONNECTED) 1] create -e /python "java"
Created /python

Print the result

image.png

4. Determine whether the node exists

private static final String IPS = "master:2181,slave1:2181,slave2:2181";
private static final int SESSIONTIMEOUT = 200;
private ZooKeeper zkClient = null;

@Before
public void contectTest() throws Exception{
    zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {

        }
    });

    System.out.println("==================");
    System.out.println(zkClient.getState());
    System.out.println("==================");
}

@Test
public void exTest() throws Exception{
    Stat exists = zkClient.exists("/test", false);
    System.out.println(exists == null ? "no" : "yes");

}

Print the result

image.png

5. Test complete code

package com.example.demo; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.junit.Before; import org.junit.Test; import java.util.List; public class ZKDemo { private static final String IPS = "master:2181,slave1:2181,slave2:2181"; private static final int SESSIONTIMEOUT = 200; private ZooKeeper zkClient = null; @Before public void contectTest() throws Exception{ zkClient = new ZooKeeper(IPS, SESSIONTIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { /*System.out.println(event.getType() + "--" + event.getPath()); try { zkClient.getChildren("/", true); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); * /}}}); System.out.println("=================="); System.out.println(zkClient.getState()); System.out.println("=================="); } @Test public void createTest() throws Exception{ String s = zkClient.create("/idea", "helloworld".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); System.out.println(s); } @Test public void childrenTest() throws Exception{ List<String> children = zkClient.getChildren("/", true); for (String ch : children){ System.out.println(ch); } Thread.sleep(Long.MAX_VALUE); } @Test public void exTest() throws Exception{ Stat exists = zkClient.exists("/test", false); System.out.println(exists == null ? "no" : "yes"); }}

At the end of the article’s welfare

Contains C, C ++, Java, Python, Linux, HTML, PHP and other hundreds of e-books!

Obtain method:

Search and follow the official account: Walking the Sahara in the Rain

Reply keyword: 001