先启动zookeeper服务集群。
[wangzhou@zookeeper01 logs]$ zk.sh start
查看状态
[wangzhou@zookeeper01 logs]$ zk.sh status
结果如下就说明启动成功哦(ps:集群操作这里不会的童鞋可以看看该专栏前几篇博客哟~)。
然后idea新建maven工程。
pom添加依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.7</version>
</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
按如下目录结构建立ZKClient实例。
写下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