Zookeeper [operating] in Java

First, the basic functional demo

1.1 Maven dependency information

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

1.2 code shows

public class Test001 {
    
    private static final String CONNECTSTRING = "127.0.0.1:2181";
    private static final int SESSIONTIMEOUT =  5000;
    //信号量,阻塞程序执行,用户等待zookeeper连接成功,发送成功信号,
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);
    
    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = null;
        try {
            //1.Zookeeper创建了一连接
            zooKeeper = new ZooKeeper(CONNECTSTRING, SESSIONTIMEOUT, new Watcher() {
                
                @Override
                public void process(WatchedEvent event) {
                    //监听节点是否发生变化
                    
                    // 获取事件状态
                    KeeperState keeperState = event.getState();
                    // 获取事件类型
                    EventType eventType = event.getType();
                    if (KeeperState.SyncConnected == keeperState) {
                        if (EventType.None == eventType) {
                            countDownLatch.countDown();//调用该方法会减一,如果为0的话
                            System.out.println("zk 启动连接...");
                        }

                    }
                    
                }
            });
            
            
            // 2.
            //节点类型:
            // 1. CreateMode . EPHEMERAL创建- -个临时节点
            // 2.CreateMode. EPHEMERAL _SEQUENTIAL 如果节点发生重复的情况下,会自动id自增保证唯- -性
            // 3.CreateMode . PERSISTENT持久类型永久保存在硬盘上
            // 4.CreateMode. PERSISTENT SEQUENTIAL持久类型如果节点发生重复的情况下,会自动id自增保证唯一性
            
            countDownLatch.await();//如果计数器不为0,则一直等待
            String nodeResult = zooKeeper.create("/test", "zhangsan".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("节点名称:"+nodeResult);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(zooKeeper!=null) {
                zooKeeper.close();
            }
            
        }
        
    }
}

Method Description

创建节点(znode) 方法:
create(String path, byte[] data, List<ACL> acl, CreateMode createMode) throws KeeperException, InterruptedException

提供了两套创建节点的方法,同步和异步创建节点方式。
同步方式:
* 参数1,节点路径名称 : InodeName (不允许递归创建节点,也就是说在父节点不存在的情况下,不允许创建子节点)
* 参数2,节点内容: 要求类型是字节数组(也就是说,不支持序列化方式,如果需要实现序列化,可使用java相关序列化框架,如Hessian、Kryo框架)
* 参数3,节点权限: 使用Ids.OPEN_ACL_UNSAFE开放权限即可。(这个参数一般在权展
没有太高要求的场景下,没必要关注)
* 参数4,节点类型: 创建节点的类型: CreateMode,提供四种节点类型
   * PERSISTENT                   持久化节点
   * PERSISTENT_SEQUENTIAL        顺序自动编号持久化节点,这种节点会根据当前已存在的节点数自动加 1
   * EPHEMERAL                    临时节点, 客户端session超时这类节点就会被自动删除
   * EPHEMERAL_SEQUENTIAL         临时自动编号节点

1.3 Zookeeper create node information

//1. 创建持久节点,并且允许任何服务器可以操作
String result = zk.create("/haoworld", "Lasting".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("result:" + result);
//2. 创建临时节点
String result = zk.create("/haoworld_tmp", "temp".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("result:" + result);

Two, Watcher

  • In ZooKeeper, the Watcher interface class is used to represent a standard event handler, which defines an event notification associated logic, comprising two KeeperState EventType and enumerated classes, representing the state notification and event type, the event also defines callback method: process (WatchedEvent event).

2.1 What is the Watcher Interface

Event types represent the same meaning in different states in different notifications, Table 7-3 lists the common status and event notification type.
Watcher notify state and the type of event list

![-w735](media/15681306896776/15681308320378.jpg)

ZooKeeper table lists the most common of several notification status and event type.

  • Callback method process ()
    • The process method is a method Watcher callback interface, when sending a Watcher ZooKeeper event notifications to the client, the client will perform the corresponding process callback method, enabling handling of the incident. The process method defined as follows:
  • abstract public void process(WatchedEvent event);
    • Define the callback method is very simple, we look at the focus method parameter definitions: WatchedEvent. WatchedEvent contains three basic properties of each event: notification state (keeperState), event type (the EventType) and a node of the path (path) ,. ZooKeeper using WatchedEvent objects to encapsulate and passed to the event server Watcher, thereby facilitating callback method of the server process to handle the event.
      Mentioned WatchedEvent, have to speak under WatcherEvent entity. Generally speaking, the two represents the same thing, is a service package to end the event. The difference is, WatchedEvent is a logical event, for the server and client programs perform logical objects needed in the process, because the WatcherEvent implements serialization interface can be used for network transmission.
      After generating WatchedEvent server events, calls getWrapper method to package itself as a sequence of events WatcherEvent, for transmission to the client over the network. After the client receives this event object to the server, will first be reduced to a WatchedEvent WatcherEvent event, and passed to the process method of treatment, it is possible to process callback method parse the complete end of the event according to the service parameters.
      One thing to note is that both WatchedEvent or WatcherEvent, which are packaged machine ZooKeeper server-side event and simple. For example, when the data / zk-book this node is changed, the server sends to the client a "znode data content change" event, the client can receive only the channel as follows

2.2 Watcher Code

public class ZkClientWatcher implements Watcher {
        // 集群连接地址
        private static final String CONNECT_ADDRES = "192.168.110.159:2181,192.168.110.160:2181,192.168.110.162:2181";
        // 会话超时时间
        private static final int SESSIONTIME = 2000;
        // 信号量,让zk在连接之前等待,连接成功后才能往下走.
        private static final CountDownLatch countDownLatch = new CountDownLatch(1);
        private static String LOG_MAIN = "【main】 ";
        private ZooKeeper zk;

    public void createConnection(String connectAddres, int sessionTimeOut) {
        try {
            zk = new ZooKeeper(connectAddres, sessionTimeOut, this);
            System.out.println(LOG_MAIN + "zk 开始启动连接服务器....");
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean createPath(String path, String data) {
        try {
            this.exists(path, true);
            this.zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println(LOG_MAIN + "节点创建成功, Path:" + path + ",data:" + data);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断指定节点是否存在
     * 
     * @param path
     *            节点路径
     */
    public Stat exists(String path, boolean needWatch) {
        try {
            return this.zk.exists(path, needWatch);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean updateNode(String path,String data) throws KeeperException, InterruptedException {
        exists(path, true);
        this.zk.setData(path, data.getBytes(), -1);
        return false;
    }

    public void process(WatchedEvent watchedEvent) {

        // 获取事件状态
        KeeperState keeperState = watchedEvent.getState();
        // 获取事件类型
        EventType eventType = watchedEvent.getType();
        // zk 路径
        String path = watchedEvent.getPath();
        System.out.println("进入到 process() keeperState:" + keeperState + ", eventType:" + eventType + ", path:" + path);
        // 判断是否建立连接
        if (KeeperState.SyncConnected == keeperState) {
            if (EventType.None == eventType) {
                // 如果建立建立成功,让后程序往下走
                System.out.println(LOG_MAIN + "zk 建立连接成功!");
                countDownLatch.countDown();
            } else if (EventType.NodeCreated == eventType) {
                System.out.println(LOG_MAIN + "事件通知,新增node节点" + path);
            } else if (EventType.NodeDataChanged == eventType) {
                System.out.println(LOG_MAIN + "事件通知,当前node节点" + path + "被修改....");
            }
            else if (EventType.NodeDeleted == eventType) {
                System.out.println(LOG_MAIN + "事件通知,当前node节点" + path + "被删除....");
            }

        }
        System.out.println("--------------------------------------------------------");
    }

    public static void main(String[] args) throws KeeperException, InterruptedException {
        ZkClientWatcher zkClientWatcher = new ZkClientWatcher();
        zkClientWatcher.createConnection(CONNECT_ADDRES, SESSIONTIME);
    //      boolean createResult = zkClientWatcher.createPath("/p15", "pa-644064");
            zkClientWatcher.updateNode("/pa2","7894561");
        }
    
    }

Guess you like

Origin www.cnblogs.com/haoworld/p/zookeeper-zaijava-zhong-de-cao-zuo.html