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+"}");
}
}
推荐阅读
-
【Web API系列教程】3.1 — 实战:处理数据(创建项目)
-
【Web API系列教程】3.7 — 实战:处理数据(创建UI视图)
-
【Web API系列教材】1.3 — 实战:用ASP.NET Web API和Angular.js创建单页面应用程序(上)
-
【Web API系列教材】1.3 — 实战:用ASP.NET Web API和Angular.js创建单页面应用程序(下)
-
.NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据
-
【Web API系列教程】1.3 — 实战:用ASP.NET Web API和Angular.js创建单页面应用程序(上)...
-
Elasticsearch 5.X Java API 创建客户端
-
ZooKeeper API实战创建客户端
-
Elasticsearch Java API 的使用(1)—创建客户端
-
【Web API系列教程】3.5 — 实战:处理数据(创建数据传输对象)