1、添加依赖
<dependencies>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
2、操作zookeeper节点
package com.cn.willy.com.cn.curator.willy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
public class ZookeeperFactory {
public static void main(String[] args) {
//建立zookeeper连接
CuratorFramework factory = CuratorFrameworkFactory.builder()
.connectString("192.168.43.135:2181")
.connectionTimeoutMs(5000)
.retryPolicy(new RetryOneTime(300))
.namespace("fsm")
.build();
//打开连接
factory.start();
try{
//节点存在性查询
System.out.println("check node exists");
Stat stat = factory.checkExists()
.forPath("/node");
if(stat == null){
//创建节点
System.out.println("create node");
factory.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath("/node","this is curator".getBytes());
}
//获取节点数据
System.out.println("get node");
byte[] bytes = factory.getData().forPath("/node");
System.out.println(new String(bytes));
//设置节点数据
System.out.println("update node");
factory.setData().forPath("/node","set node".getBytes());
byte[] bytes1 = factory.getData().forPath("/node");
System.out.println(new String(bytes1));
//删除节点数据
System.out.println("delete node");
Void aVoid = factory.delete()
.deletingChildrenIfNeeded()
.forPath("/node");
}catch (Exception e){
e.printStackTrace();
}
//关闭连接
System.out.println("start");
factory.close();
}
}