1.引入Curator的maven依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.4.2</version>
</dependency>
重试具体实现类
ExponentialBackoffRetry
RetryNTimes
RetryOneTime
RetryUntilElapsed
curator创建客户端package com.chongshi.test;
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.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
public class CuratorExample {
// 服务器IP&端口
private static final String connectString = "127.0.0.1:2181";
// 会话超时时间
private static final int sessionTimeoutMs = 1000;
// 连接超时时间
private static final int connectionTimeoutMs = 10000;
// 重试策略
/**
* ExponentialBackoffRetry重试指定的次数, 且每一次重试之间停顿的时间逐渐增加
* ,RetryNTimes指定最大重试次数的重试策略 RetryOneTime仅重试一次 RetryUntilElapsed
*/
private static RetryPolicy retryPolicy = null;
private static CuratorFramework cf = null;
static {
/**
* 重试几次,重试间隔时间
*/
// retryPolicy = new RetryNTimes(1, 1000);
// retryPolicy = new RetryOneTime(1000);
/**
* maxElapsedTimeMs,sleepMsBetweenRetries retryPolicy = new
* RetryUntilElapsed(maxElapsedTimeMs, sleepMsBetweenRetries);
*/
// 初试sleep时间,最大重试次数,最长休眠时间,每次重试,睡眠时间增加
retryPolicy = new ExponentialBackoffRetry(1000, 3, 5000);
cf = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs,
connectionTimeoutMs, retryPolicy);
cf.start();
}
/**
* 自动创建父级节点 可选CreateModel
*
* @param path
* @param values
* @param createMode
*/
public void addOrUpdateNode(String path, String values,
CreateMode createMode) {
try {
cf.create().creatingParentsIfNeeded().withMode(createMode)
.forPath(path, values.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除 例子,不可以直接使用
*
* @param path
* @param version
*/
public void dele(String path, int version) {
/**
*
*/
// 递归删除子结点
try {
cf.delete().deletingChildrenIfNeeded().forPath(path);
// 制定的version
cf.delete().withVersion(version);
// 只要客户端会话一直有效,那么就会在后台持续删除
cf.delete().guaranteed();
cf.delete().deletingChildrenIfNeeded();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object getData(String path) {
String msg = "";
try {
msg = new String(cf.getData().forPath(path));
Stat sta = new Stat();
/**
* 取得服务端返回的stat
*/
msg = new String(cf.getData().storingStatIn(sta).forPath(path));
} catch (Exception e) {
e.printStackTrace();
}
return msg;
}
/**
* 设置数据
*
* @param path
* @param value
* @param version
*/
public void setData(String path, String value, int version) {
try {
cf.setData().forPath(path, value.getBytes());
cf.setData().withVersion(version);
} catch (Exception e) {
}
}
public static void main(String[] args) {
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
使用异步的调用方法:
package com.chongshi.test;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
public class CuratorExampleAsync {
// 服务器IP&端口
private static final String connectString = "127.0.0.1:2181";
// 会话超时时间
private static final int sessionTimeoutMs = 1000;
// 连接超时时间
private static final int connectionTimeoutMs = 10000;
// 重试策略
/**
* ExponentialBackoffRetry重试指定的次数, 且每一次重试之间停顿的时间逐渐增加
* ,RetryNTimes指定最大重试次数的重试策略 RetryOneTime仅重试一次 RetryUntilElapsed
*/
private static RetryPolicy retryPolicy = null;
private static CuratorFramework cf = null;
static {
/**
* 重试几次,重试间隔时间
*/
// retryPolicy = new RetryNTimes(1, 1000);
// retryPolicy = new RetryOneTime(1000);
/**
* maxElapsedTimeMs,sleepMsBetweenRetries retryPolicy = new
* RetryUntilElapsed(maxElapsedTimeMs, sleepMsBetweenRetries);
*/
// 初试sleep时间,最大重试次数,最长休眠时间,每次重试,睡眠时间增加
retryPolicy = new ExponentialBackoffRetry(1000, 3, 5000);
cf = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs,
connectionTimeoutMs, retryPolicy);
}
/**
* 自动创建父级节点 可选CreateModel
*
* @param path
* @param values
* @param createMode
*/
public void addOrUpdateNode(String path, String values,
CreateMode createMode) {
System.err.println(Thread.currentThread().getName() + "@@@");
// 没有自定义线程
try {
cf.create().creatingParentsIfNeeded().withMode(createMode)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework cf,
CuratorEvent event) throws Exception {
System.err.println(Thread.currentThread().getName()
+ "fff");
System.err.println("type:" + event.getType()
+ "state:" + event.getResultCode());
}
}).forPath(path, values.getBytes());
Executor executor = Executors.newFixedThreadPool(2);
// 自定义线程
cf.create().creatingParentsIfNeeded().withMode(createMode)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework cf,
CuratorEvent event) throws Exception {
System.err.println(Thread.currentThread().getName()
+ "fff11");
System.err.println("type:" + event.getType()
+ "state111:" + event.getResultCode());
}
}, executor).forPath(path, values.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
cf.start();
CuratorExampleAsync async = new CuratorExampleAsync();
async.addOrUpdateNode("/patzheng", "zhenglong",
CreateMode.EPHEMERAL);
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.chongshi.test;
import java.util.List;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
public class CuratorWatchExample {
// 服务器IP&端口
private static final String connectString = "127.0.0.1:2181";
// 会话超时时间
private static final int sessionTimeoutMs = 1000;
// 连接超时时间
private static final int connectionTimeoutMs = 10000;
private static String path = "/watcher/test";
private static final String path1 = "/watcher/test1";
// 重试策略
/**
* ExponentialBackoffRetry重试指定的次数, 且每一次重试之间停顿的时间逐渐增加
* ,RetryNTimes指定最大重试次数的重试策略 RetryOneTime仅重试一次 RetryUntilElapsed
*/
private static RetryPolicy retryPolicy = null;
private static CuratorFramework cf = null;
static {
/**
* 重试几次,重试间隔时间
*/
// retryPolicy = new RetryNTimes(1, 1000);
// retryPolicy = new RetryOneTime(1000);
/**
* maxElapsedTimeMs,sleepMsBetweenRetries retryPolicy = new
* RetryUntilElapsed(maxElapsedTimeMs, sleepMsBetweenRetries);
*/
// 初试sleep时间,最大重试次数,最长休眠时间,每次重试,睡眠时间增加
retryPolicy = new ExponentialBackoffRetry(1000, 3, 5000);
cf = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs,
connectionTimeoutMs, retryPolicy);
}
public void wathcherDemo() {
// 启动客户端
cf.start();
try {
cf.create().creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL)
.forPath(path, "watcher.test".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
final NodeCache nodeCache = new NodeCache(cf, path);
try {
nodeCache.start();
} catch (Exception e) {
e.printStackTrace();
}
/**
* 使用Curator的客户端和路径获取nodeCache
* nodeCache设置监听处理数据变化。变化之后nodeCache可以获取到数据使用geyCurrentData
*
*/
nodeCache.getListenable().addListener(new NodeCacheListener() {
public void nodeChanged() throws Exception {
System.err.println("now date is "
+ new String(nodeCache.getCurrentData().getData()));
}
});
// 节点如果不存在也可以加监听,等到几点被创建就会增加监听
try {
cf.setData().forPath(path, "new test ".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
final NodeCache nodeCache1 = new NodeCache(cf, path1);
try {
// 记得启动
nodeCache1.start();
} catch (Exception e) {
e.printStackTrace();
}
nodeCache1.getListenable().addListener(new NodeCacheListener() {
public void nodeChanged() throws Exception {
System.err.println("节点不存在");
}
});
try {
Thread.sleep(2000);
// cf.delete().guaranteed().forPath(path);
} catch (Exception e) {
e.printStackTrace();
}
}
public void childWathcherDemo() {
// 启动客户端
cf.start();
path = "/config";
try {
cf.create().creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, "watcher.child.test".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
final NodeCache nodeCache = new NodeCache(cf, path);
try {
nodeCache.start();
} catch (Exception e) {
e.printStackTrace();
}
// 只能监控一级子目录
final PathChildrenCache childrenCache = new PathChildrenCache(cf, path,
true);
/**
* NORMAL: 初始时为空。 BUILD_INITIAL_CACHE: 在这个方法返回之前调用rebuild()。
* POST_INITIALIZED_EVENT:
* 当Cache初始化数据后发送一个PathChildrenCacheEvent.Type#INITIALIZED事件
*/
try {
childrenCache.start(StartMode.NORMAL);
} catch (Exception e1) {
e1.printStackTrace();
}
childrenCache.getListenable().addListener(
new PathChildrenCacheListener() {
public void childEvent(CuratorFramework client,
PathChildrenCacheEvent event) throws Exception {
List<ChildData> list = childrenCache.getCurrentData();
switch (event.getType()) {
case CHILD_ADDED:
System.err.println("children add");
break;
case CHILD_REMOVED:
System.err.println("children remove");
break;
case CHILD_UPDATED:
System.err.println("children update");
break;
default:
break;
}
}
});
}
public static void main(String[] args) {
CuratorWatchExample curatorWatchExample = new CuratorWatchExample();
curatorWatchExample.childWathcherDemo();
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (Exception e) {
// TODO: handle exception
}
}
}