使用zookeeper原生API链接ZK集群进行基本API演示

上一篇发布了近期的面试总结-Mysql篇,最近在读《从Paxos到Zookeeper分布式一致性原理与实践》的电子书,从上面学到不少,因此将部分api演示从头演练一遍形成demo代码。

zookeeper初始化构造方法

package com.coderman.zookeeper.clusterdemo.version2;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @description:
 * @author: Fanchunshuai
 * @time: 2020/2/10 15:51
 */
public class ZKConstructDemo implements Watcher {
    private static StringBuffer buffer = new StringBuffer();
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static final int SESSION_TIMEOUT = 5000;
    protected  static ZooKeeper zooKeeper;

    static {
        buffer.append("192.168.1.224:2184,");
        buffer.append("192.168.1.224:2181,");
        buffer.append("192.168.1.224:2182,");
        buffer.append("192.168.1.224:2183,");
        buffer.append("192.168.1.224:2185");
    }
    public static void main(String[] args) {
        try {
            //第一种初始化接口
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo());
            //第二种初始化接口增加了两个参数,为了复用session会话和密码
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo(),zooKeeper.getSessionId(),zooKeeper.getSessionPasswd());

            System.out.println(zooKeeper.getState());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            countDownLatch.await();
            System.out.println("zookeeper session established...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("received watch event = "+watchedEvent);
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            countDownLatch.countDown();
        }
    }
}

zookeeper创建API的接口方法

package com.coderman.zookeeper.clusterdemo.version2;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @description:
 * @author: Fanchunshuai
 * @time: 2020/2/10 16:47
 */

/**
 * 节点创建API
 * zookeeper的节点创建api有两个重载方法
 * 一个是同步调用,一个是异步调用
 * 创建节点的参数如下:
 * path:需要创建节点的路径 如/zookeeper/config
 * data[]:节点创建后的初始内容
 * acl:节点的ACL策略,是List类型,已经通过ZooDefs.Ids类初始化好了
 * createMode:创建节点的类型或者模式,是枚举类型,通过CreateMode枚举类初始化好了
 * cb:回调函数
 * ctx:传递一个上下文对象,在回调方法执行的时候使用
 * <p>
 * 需要注意的是:无论是同步接口还是异步接口,zookeeper都不支持递归创建,即无法在父节点不存在的情况下创建子节点。
 * 如果节点已经存在,那么创建同名节点将会抛出NodeExitsException异常。
 * <p>
 * 同步调用演示
 */
public class ZKCreateAPIDemo implements Watcher {
    private static StringBuffer buffer = new StringBuffer();
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static final int SESSION_TIMEOUT = 5000;
    protected static ZooKeeper zooKeeper;

    static {
        buffer.append("192.168.1.224:2184,");
        buffer.append("192.168.1.224:2181,");
        buffer.append("192.168.1.224:2182,");
        buffer.append("192.168.1.224:2183,");
        buffer.append("192.168.1.224:2185");
    }

    public static void main(String[] args) {
        //createSyncCall();
        createAsyncCall();
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            countDownLatch.countDown();
        }
    }

    /**
     * 同步调用演示
     */
    private static void createSyncCall() {
        try {
            //第一种初始化接口
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo());
            //第二种初始化接口增加了两个参数,为了复用session会话和密码
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo(), zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());

            String path = "/hadoop";
            byte[] data = "hadooper".getBytes();
            //1.创建一个临时节点
            String response = zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            System.out.println("response = " + response);

            String path2 = "/hadoop2";
            byte[] data2 = "hadooper2".getBytes();
            //2.创建一个临时顺序节点
            String response2 = zooKeeper.create(path2, data2, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println("response2 = " + response2);

            //3.创建一个持久节点
            String path3 = "/hadoop3";
            byte[] data3 = "hadooper3".getBytes();
            String response3 = zooKeeper.create(path3, data3, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("response3 = " + response3);
            //4.创建一个持久顺序节点
            String path4 = "/hadoop4";
            byte[] data4 = "hadooper4".getBytes();
            String response4 = zooKeeper.create(path4, data4, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            System.out.println("response4 = " + response3);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
        try {
            countDownLatch.await();
            System.out.println("zookeeper session established...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步调用演示
     */
    private static void createAsyncCall() {
        String path = "/hadoopsync";
        byte[] data = "hadoopersync".getBytes();
        try {
            //第一种初始化接口
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo());
            //第二种初始化接口增加了两个参数,为了复用session会话和密码
            zooKeeper = new ZooKeeper(buffer.toString(), SESSION_TIMEOUT, new ZKConstructDemo(), zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //1.创建一个临时节点
        zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new IStringCallBack(), "the context");
        //1.创建一个临时节点
        zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,
                new IStringCallBack(), "the context");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串回调接口,除了这种类型的回调接口之外
     * 如ACLCallback,DataCallback等。
     */
    static class IStringCallBack implements AsyncCallback.StringCallback {

        /**
         * @param rc   响应码 0:接口调用成功 -4:客户端和服务端链接已经断开
         *             -110:指定节点已经存在。-112:会话已过期
         * @param path 接口调用时传入API的数据节点的路径参数值
         * @param ctx  接口调用时传入API的ctx参数值
         * @param name 实际在服务端创建的节点名
         */
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            System.out.println("create path result:["
                    + rc + ", " + path + ", " + ctx + ", real path name :" + name);
        }
    }
}
发布了166 篇原创文章 · 获赞 71 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/u010504064/article/details/104251456