Accessing ZooKeeper based on Java API

We can use the Java API to access ZooKeeper and perform some necessary operations on ZooKeeper nodes. Let's take a look at how to implement it through code.

Environmental preparation

1) First, we must ensure that ZooKeeper port 2181 has been opened. If you have not opened it yet, please execute the following instructions with the firewall enabled:

firewall-cmd --zone=public --add-port=2181/tcp --permanent

Then reload the firewall

firewall-cmd --reload

2) Start ZooKeeper

Knowledge preparation

1) Java connects to ZK. The client needs to create a ZooKeeper instance to connect to the ZK server. The ZooKeeper construction methods are as follows:

public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
 
public ZooKeeper(String connectString, int sessionTimeout,Watcher watcher,ZKClientConfig conf)
 
public ZooKeeper(String connectString, int sessionTimeout,Watcher watcher, boolean canBeReadOnly, HostProvider aHostProvider) 
 
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, HostProvider aHostProvider, ZKClientConfig clientConfig) 

Zookeeper(Arguments) Method

  • connectString: Connection server list, separated by ","
  • sessionTimeout: Heartbeat detection time period (milliseconds)
  • watcher:Event handling notifier
  • canBeReadOnly: Identifies whether the current session supports read-only
  • SessionId and  SessionPasswd: provide the sessionId and password to connect to Zookeeper, and determine the only client through these two, in order to provide repeated sessions.

The establishment of ZK client and server sessions is an asynchronous process. Our program method returns immediately after processing the client initialization, that is, the program continues to execute the code. In this way, in most cases we do not actually build a usable session. , the establishment is completed when the session life cycle is in "CONNECTING".

2) Create node (znode) method: create
provides two sets of methods for creating nodes, synchronous and asynchronous node creation methods.

Parameter 1:

Node path: /nodeName (recursive creation of nodes is not allowed, that is, when the parent node does not exist, creation of child nodes is not allowed)

Parameter 2:

Node content: The required type is a byte array (serialization is not supported. If you need to implement programming, you can use Java-related serialization frameworks, such as Hession and Kryo frameworks)

Parameter 3:

Node permissions: Use Ids.OPEN_ACL_UNSAFE to open permissions

Parameter 4:

Node type: The type of node to create: CreateMode.*

  •  persistent (persistent node)
  •  persistent_sequential (persistent sequential node)
  •  ephemeral (temporary node)
  •  ephemeral_sequential (temporary sequential node)

Parameter 5:

To register an asynchronous callback function, implement the AsynCallBack.StringCallBack interface, override the processResult(int rc, String path, Object ctx, String name) method, and execute this method after the node is created.

  • rc: The corresponding code for the server is 0, which means the call is successful, -4, which means the port is connected, -110, which means the specified node exists, and -112, which means the session has expired.
  •  path: the path parameter of the data node passed into the API when calling the interface
  •  ctx: The ctx value passed into the API for the calling interface
  •  name: The name of the node actually created on the server side

Parameter 6:

Parameters passed to the callback function, usually context information

Code

1) First we need to create a Maven project, and import the jar package required for ZooKeeper operation into its pom.xml (the version is determined by your own zk version), as follows:

<dependency>
  <groupId>org.apache.zookeeper</groupId>
  <artifactId>zookeeper</artifactId>
  <version>3.5.9</version>
</dependency>

2) Create a new test class (we use the stand-alone version here), the specific code is as follows:

package com.panziye;
 
import org.apache.zookeeper.*;
 
import java.io.IOException;
 
/**
 * <h3>zk</h3>
 *
 * @author panziye
 * @description <p></p>
 * @date 2021-04-24 22:15
 **/
public class ZKDemo implements Watcher {
    private static final int SESSION_TIMEOUT = 30000;
    public static ZooKeeper zooKeeper;
 
    public static void main(String[] args) {
        String path = "/zknode1";
        try {
            zooKeeper = new ZooKeeper("192.168.55.128:2181",SESSION_TIMEOUT,new ZKDemo());
            zooKeeper.exists(path,true);
            //创建节点
            zooKeeper.create(path,"zkcontent1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            Thread.sleep(3000);
 
            //得到节点内容
            byte[] bytes1 = zooKeeper.getData(path,null,null);
            String result1 = new String(bytes1);
            System.out.println("result1==="+result1);
 
            //设置节点内容
            zooKeeper.setData(path,"testSetData111".getBytes(),-1);
 
            //再次的带节点内容
            byte[] bytes2 = zooKeeper.getData(path,null,null);
            String result2 = new String(bytes2);
            System.out.println("result2==="+result2);
            Thread.sleep(3000);
 
            //删除节点
            zooKeeper.delete(path,-1);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }finally {
            if(zooKeeper != null){
                try {
                    zooKeeper.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
 
        }
 
    }
 
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            if(watchedEvent.getType() == Event.EventType.NodeCreated){
                //当节点创建成功时进行回调,此处进行提示打印
                System.out.println("Node created success....");
                try {
                    zooKeeper.exists(watchedEvent.getPath(),true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else if(watchedEvent.getType() == Event.EventType.NodeDeleted){
                try {
                    zooKeeper.exists(watchedEvent.getPath(),true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Node deleted success....");
            }else if(watchedEvent.getType() == Event.EventType.NodeDataChanged){
                try {
                    zooKeeper.exists(watchedEvent.getPath(),true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Node changed success....");
            }
        }
    }
}
 

3) Run the test, the results are as follows:

Access ZooKeeper based on Java API

This article was first published on Pan Ziye’s personal blog: https://www.panziye.com/bigdata/3063.html. Please indicate the source for reprinting. Thank you very much!

Guess you like

Origin blog.csdn.net/mixika99/article/details/119546716