<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.netflix.curator</groupId>
<artifactId>curator-client</artifactId>
<version>1.1.10</version>
</dependency>
- 连接
private static final String ZKINFO = "**.**.**.**:2181";
private static CuratorFramework curatorFramework;
public static CuratorFramework getInstance() {
curatorFramework = CuratorFrameworkFactory
.newClient(ZKINFO, 5000,
5000,
new org.apache.curator.retry.ExponentialBackoffRetry(1000, 3)
);
curatorFramework.start();
return curatorFramework;
}
2.创建节点
CuratorFramework curatorFramework = CuratorUtils.getInstance();
try {
String s = curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath("/curator/curator1/curator1-1/curator1-1-1", "111".getBytes());
System.out.println("创建返回值->"+s);
} catch (Exception e) {
e.printStackTrace();
}
3.删除节点
try {
curatorFramework.delete().deletingChildrenIfNeeded().forPath("/curator");
System.out.println("执行删除操作");
} catch (Exception e) {
e.printStackTrace();
}
4.查询节点
try {
Stat stat = new Stat();
byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/node01");
System.out.println(new String (bytes));
System.out.println(stat);
} catch (Exception e) {
e.printStackTrace();
}
5.更新节点
try {
Stat stat = curatorFramework.setData().forPath("/node01", "1123".getBytes());
System.out.println(stat);
} catch (Exception e) {
e.printStackTrace();
}
6.异步操作(创建)
try {
ExecutorService service = Executors.newScheduledThreadPool(2);
CountDownLatch countDown = new CountDownLatch(1);
curatorFramework.create().creatingParentContainersIfNeeded().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
System.out.println(Thread.currentThread().getName()+"->"+curatorEvent.getResultCode()+"->"+curatorEvent.getType());
countDown.countDown();
}
},service).forPath("/curator");
System.out.println("当前线程"+Thread.currentThread().getName());
countDown.await();
service.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
7.事务操作
try {
Collection<CuratorTransactionResult> commit = curatorFramework.inTransaction()
.create()
.forPath("/curatorT", "111".getBytes())
.and()
.setData()
.forPath("/curatorT", "22".getBytes())
.and()
.commit();
for(CuratorTransactionResult result:commit){
System.out.println(result.getForPath()+"->"+result.getType());
}
} catch (Exception e) {
e.printStackTrace();
}