欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ZooKeeper API实战创建客户端

程序员文章站 2022-07-05 14:18:49
...
package com.yqq.zookeeper.curd;

import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author yqq
 * @Date 2021/10/24 00:25
 * @Version 1.0
 */
public class ZKCurd {
    //定义会话的超时时间
    private final static int SESSION_TIME = 30000;
    //定义zk集群的ip地址
    private final static String ZK_SERVERS = "192.168.134.102:2181,192.168.134.103:2181,192.168.134.104:2181";
    //日志对象
    private final static Logger LOGGER = Logger.getLogger(ZKCurd.class);
    private ZooKeeper zooKeeper = null;
    private Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            LOGGER.info("event:"+watchedEvent.toString());
        }
    };
    @Before
    public void connect() throws IOException {
        zooKeeper = new ZooKeeper(ZK_SERVERS,SESSION_TIME,watcher);
        //获取当前的会话sessionID
        Long sessionId = zooKeeper.getSessionId();
        LOGGER.info("sessionId:"+sessionId);
        System.out.println("zookeeper:"+zooKeeper);
    }
    @After
    public void close() throws InterruptedException {
        zooKeeper.close();
    }
    /**
     * 创建节点
     * final String path:要创建的节点的全路径
     * byte data[]:节点中数据内容
     * List<ACL> acl:节点权限
     * CreateModel createModel:节点类型
     * *PERSISTENT:普通持久节点
     * *PERSISTENT_SEQUENTIAL:普通临时持久节点
     * *EPHEMERAL:普通临时节点
     * *EPHEMERAL_SEQUENTIAL:普通临时有序节点
     */
    @Test
    public void create() {
        String result = null;
        try {
//            result = zooKeeper.create("/James","good nice".getBytes(StandardCharsets.UTF_8),
//                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            result = zooKeeper.create("/JamesLLL","good nice".getBytes(StandardCharsets.UTF_8),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        LOGGER.info("create result:{"+result+"}");
    }
}