CuratorFramework使用

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

CuratorFramework使⽤
CuratorFramework
Framework
是ZooKeeper Client更⾼的抽象API
⾃动连接管理:
1. 当ZooKeeper客户端内部出现异常, 将⾃动进⾏重连或重试, 该过程对外⼏乎完全透明
2. 监控节点数据变化事件NodeDataChanged,需要时调⽤updateServerList()⽅法
3. Curator recipes⾃动移除监控
更清晰的API: 简化了ZooKeeper原⽣的⽅法, 事件等, 提供流式fluent的接⼝
提供Recipes实现 : 选举,共享锁,路径cache,分布式队列,分布式优先队列等
CuratorFrameworkFactory类提供了两个⽅法, ⼀个⼯⼚⽅法newClient, ⼀个构建⽅法build. 使⽤⼯⼚⽅法newClient可以创建⼀个默认的实例, ⽽build构建⽅法可以对实例进⾏定制. 当CuratorFramework实例构建完成, 紧接着调⽤start()⽅法, 在应⽤结束的时候, 需要调⽤close()⽅法. CuratorFramework是线程安全的. 在⼀个应⽤中可以共享同⼀个zk集群的CuratorFramework.
CuratorFramework API采⽤了连贯风格的接⼝(Fluent Interface). 所有的操作⼀律返回构建器, 当所有元素加在⼀起之后, 整个⽅法看起来就像⼀个完整的句⼦. ⽐如下⾯的操作:
client.create().forPath("/head")
client.delete().inBackground().forPath("/head")
client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child")
client.getData().watched().inBackground().forPath("/test")
⽅法说明:
create(): 发起⼀个create操作. 可以组合其他⽅法 (⽐如mode 或background) 最后以forPath()⽅法结尾
delete(): 发起⼀个删除操作. 可以组合其他⽅法(version 或background) 最后以forPath()⽅法结尾
checkExists(): 发起⼀个检查ZNode 是否存在的操作. 可以组合其他⽅法(watch 或background) 最后以forPath()⽅法结尾
getData(): 发起⼀个获取ZNode数据的操作. 可以组合其他⽅法(watch, background 或get stat) 最后以forPath()⽅法结尾
setData(): 发起⼀个设置ZNode数据的操作. 可以组合其他⽅法(version 或background) 最后以forPath()⽅法结尾
getChildren(): 发起⼀个获取ZNode⼦节点的操作. 可以组合其他⽅法(watch, background 或get stat) 最后以forPath()⽅法结尾inTransaction(): 发起⼀个ZooKeeper事务. 可以组合create, setData, check, 和/或delete 为⼀个操作, 然后commit() 提交
通知(Notification)
通过ClientListener实现。

通过CuratorFramework实例⾥的addListener()注册listener. listener实现以下⽅法:
- eventReceived() 当⼀个后台操作完成或者指定的watch被触发时该⽅法被调⽤
CuratorEvent
CuratorEvent(在以前版本为ClientEvent)是对各种操作触发相关事件对象(POJO)的⼀个完整封装, ⽽事件对象的内容跟事件类型相关, 事件类型可通过getType()获得。

下⾯是对应关系:
名称空间(Namespace)
因为⼀个zk集群会被多个应⽤共享, 为了避免各个应⽤的zk patch冲突, Curator Framework内部会给每⼀个Curator Framework实例分配⼀个namespace(可选). 这样你在create ZNode的时候都会⾃动加上这个namespace作为这个node path的root. 使⽤代码如下: CuratorFramework client = CuratorFrameworkFactory.builder().namespace("MyApp") ... build();

client.create().forPath("/test", data);
// 实际上节点路径为: "/MyApp/test"
创建builder时不是调⽤build()⽽是调⽤buildTemp()。

3分钟不活动连接就被关闭,也可以指定不活动的时间。

它只提供了下⾯⼏个⽅法:/**
* Stop the client
*/
public void close();
/**
* Start a transaction builder
*
* @return builder object
* @throws Exception errors
*/
public CuratorTransaction inTransaction() throws Exception;
/**
* Start a get data builder
*
* @return builder object
* @throws Exception errors
*/
public TempGetDataBuilder getData() throws Exception;
创建实例
两种⽅法,newClient()或build(),实例如下,来⾃于官⽹
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* /licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package framework;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class CreateClientExamples
{
public static CuratorFramework createSimple(String connectionString)
{
// these are reasonable arguments for the ExponentialBackoffRetry. The first
// retry will wait 1 second - the second will wait up to 2 seconds - the
// third will wait up to 4 seconds.
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
// The simplest way to get a CuratorFramework instance. This will use default values.
// The only required arguments are the connection string and the retry policy
return CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
}
public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs) {
// using the CuratorFrameworkFactory.builder() gives fine grained control
// over creation options. See the CuratorFrameworkFactory.Builder javadoc
// details
return CuratorFrameworkFactory.builder()
.connectString(connectionString)
.retryPolicy(retryPolicy)
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs)
// etc. etc.
.build();
}
}
CRUD操作,来⾃于官⽹
package com.colobu.zkrecipe.framework;
import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;
public class CrudExample {
public static void main(String[] args) {
}
public static void create(CuratorFramework client, String path, byte[] payload) throws Exception {
// this will create the given ZNode with the given data
client.create().forPath(path, payload);
}
public static void createEphemeral(CuratorFramework client, String path, byte[] payload) throws Exception {
// this will create the given EPHEMERAL ZNode with the given data
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload);
}
public static String createEphemeralSequential(CuratorFramework client, String path, byte[] payload) throws Exception {
// this will create the given EPHEMERAL-SEQUENTIAL ZNode with the given
// data using Curator protection.
return client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, payload);
}
public static void setData(CuratorFramework client, String path, byte[] payload) throws Exception {
// set data for the given node
client.setData().forPath(path, payload);
}
public static void setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception {
// this is one method of getting event/async notifications
CuratorListener listener = new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
// examine event for details
}
};
client.getCuratorListenable().addListener(listener);
// set data for the given node asynchronously. The completion
// notification
// is done via the CuratorListener.
client.setData().inBackground().forPath(path, payload);
}
public static void setDataAsyncWithCallback(CuratorFramework client, BackgroundCallback callback, String path, byte[] payload) throws Exception { // this is another method of getting notification of an async completion
client.setData().inBackground(callback).forPath(path, payload);
}
public static void delete(CuratorFramework client, String path) throws Exception {
// delete the given node
client.delete().forPath(path);
}
public static void guaranteedDelete(CuratorFramework client, String path) throws Exception {
// delete the given node and guarantee that it completes
client.delete().guaranteed().forPath(path);
}
public static List<String> watchedGetChildren(CuratorFramework client, String path) throws Exception {
/**
* Get children and set a watcher on the node. The watcher notification
* will come through the CuratorListener (see setDataAsync() above).
*/
return client.getChildren().watched().forPath(path);
}
public static List<String> watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception {
/**
* Get children and set the given watcher on the node.
*/
return client.getChildren().usingWatcher(watcher).forPath(path);
}
}
事务
package com.colobu.zkrecipe.framework;
import java.util.Collection;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.curator.framework.api.transaction.CuratorTransactionFinal;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
public class TransactionExample {
public static void main(String[] args) {
}
public static Collection<CuratorTransactionResult> transaction(CuratorFramework client) throws Exception {
// this example shows how to use ZooKeeper's new transactions
Collection<CuratorTransactionResult> results = client.inTransaction().create().forPath("/a/path", "some data".getBytes()) .and().setData().forPath("/another/path", "other data".getBytes())
.and().delete().forPath("/yet/another/path")
.and().commit(); // IMPORTANT! The transaction is not submitted until commit() is called
for (CuratorTransactionResult result : results) {
System.out.println(result.getForPath() + " - " + result.getType());
}
return results;
}
/*
* These next four methods show how to use Curator's transaction APIs in a
* more traditional - one-at-a-time - manner
*/
public static CuratorTransaction startTransaction(CuratorFramework client) {
// start the transaction builder
return client.inTransaction();
}
public static CuratorTransactionFinal addCreateToTransaction(CuratorTransaction transaction) throws Exception {
// add a create operation
return transaction.create().forPath("/a/path", "some data".getBytes()).and();
}
public static CuratorTransactionFinal addDeleteToTransaction(CuratorTransaction transaction) throws Exception {
// add a delete operation
return transaction.delete().forPath("/another/path").and();
}
public static void commitTransaction(CuratorTransactionFinal transaction) throws Exception {
// commit the transaction
mit();
}
}
⾃⼰写的练习
1) 新建 maven项⽬,添加依赖,添加curator-recipes即可
<dependency >
<groupId >org.apache.curator </ groupId>
<artifactId > curator-recipes</ artifactId >
<version >2.6.0 </ version>
</dependency >
2) 采⽤CuratorFrameworkFactory.newClient() 或者 build() ⽅式创建CuratorFramework实例,如下所⽰:RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client;
// client= CuratorFrameworkFactory.newClient(CONNECTSTRING, retryPolicy);
client=CuratorFrameworkFactory. builder().
connectString( CONNECTSTRING )
.connectionTimeoutMs(30000)
.sessionTimeoutMs(30000)
.canBeReadOnly( false ).retryPolicy(retryPolicy)
.namespace( NAMESPACE )
.defaultData( null )
.build();
3) client.start() 启动,结束时调⽤client.close() 关闭
4) 通过fluent⽅式进⾏相关操作,如下增删改查:
client.create().forPath( PATH, "hello world" .getBytes());
byte [] bs=client.getData().forPath( PATH);
System. out.println( "新建的节点,data为: " + new String(bs));
client.setData().forPath( PATH ,"hello china".getBytes());
// 由于是在background模式下获取的data,此时的 bs可能为null
byte [] bs2=client.getData().watched().inBackground().forPath( PATH);
System. out.println( "新修改的节点,data为: " + new String(bs2!=null ? bs2 : new byte[0]));
client.delete().forPath( PATH );
完整代码如下:
package curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.data.Stat;
public class CuratorClientExample {
public static String CONNECTSTRING= "127.0.0.1:2181";
public static String PATH= "/crud";
public static String NAMESPACE= "fortest";
public static void main(String[] args) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client;
// client= CuratorFrameworkFactory.newClient(CONNECTSTRING, retryPolicy);
client=CuratorFrameworkFactory. builder().
connectString( CONNECTSTRING )
.connectionTimeoutMs(30000)
.sessionTimeoutMs(30000)
.canBeReadOnly( false ).retryPolicy(retryPolicy)
.namespace( NAMESPACE )
.defaultData( null )
.build();
client.start();
try {
client.create().forPath( PATH ,"hello world".getBytes());
byte [] bs=client.getData().forPath( PATH);
System. out .println("新建的节点,data为: " + new String(bs));
client.setData().forPath( PATH ,"hello china".getBytes());
// 由于是在background模式下获取的data,此时的 bs可能为null
byte [] bs2=client.getData().watched().inBackground().forPath( PATH);
System. out .println("新修改的节点,data为: " + new String(bs2!=null ? bs2 : new byte[0])); client.delete().forPath( PATH );
Stat stat=client.checkExists().forPath( PATH );
// Stat 就是对zonde所有属性的⼀个映射, stat=null表⽰节点不存在!
System. out .println(stat);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
CloseableUtils. closeQuietly(client);
}
}
}。

相关文档
最新文档