前 言
作者简介:半旧518,长跑型选手,立志坚持写10年博客,专注于java后端
☕专栏简介:深入、全面、系统的介绍微服务常用技术栈zookeeper知识
文章简介:本文将深入、全面介绍使用zookeeper的客户端API远程操作zookeeper服务器新建节点,建议收藏备用,创作不易,敬请三连哦
文章推荐:
zookeeper入门到精通01——zookeeper入门
zookeeper入门到精通02——zookeeper的本地安装操作
zookeeper入门到精通03——zookeeper集群搭建
zookeeper入门到精通04——zookeeper集群选举与集群操作
Zookeeper入门到精通05——Zookeeper客户端命令行操作
先启动zookeeper服务集群。
[wangzhou@zookeeper01 logs]$ zk.sh start
查看状态
[wangzhou@zookeeper01 logs]$ zk.sh status
结果如下就说明启动成功哦(ps:集群操作这里不会的童鞋可以看看该专栏前几篇博客哟~)。
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>RELEASEversion>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.8.2version>
dependency>
<dependency>
<groupId>org.apache.zookeepergroupId>
<artifactId>zookeeperartifactId>
<version>3.5.7version>
dependency>
dependencies>
在项目的 src/main/resources 目录下,新建一个文件,命名为“log4j.properties”,在文件中填入。
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c]- %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c]- %m%n
写下demo案例。
public class ZKClient {
ZooKeeper client;
@Before
public void init() throws IOException {
// 注意逗号后不要加空格,严格按照格式,在下面写自己对应得zookeeper服务集群得ip
//端口号如不指定,默认未2181
String connectString="192.168.106.43:2182,192.168.106.44:2182,192.168.106.45:2182";
int sessionTimeout = 2000;
client = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
@Test
public void create() throws InterruptedException, KeeperException {
//参数解释:
// path:新建节点路径, data:zookeeper.avi, 控制方式:OPEN_ACL_UNSAFE,节点类型:PERSISTENT
String nodeCreated = client.create("/wangzhou", "zookeeper.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
启动zookeeper客户端,确定节点数据是否成功插入。
[zk: localhost:2181(CONNECTED) 5] get -s /sanguo2
zookeeper.avi
cZxid = 0xa0000000a
ctime = Tue Jun 21 06:24:15 PDT 2022
mZxid = 0xa0000000a
mtime = Tue Jun 21 06:24:15 PDT 2022
pZxid = 0xa0000000a
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 13
numChildren = 0