本文共 924 字,大约阅读时间需要 3 分钟。
Curator框架的目的是减少用户的复杂度,毕竟原生的Zookeeper难以使用。
这里举一个使用例子。
// 以下代码与192.168.1.101:2181建立了连接
CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.1.101:2181", new ExponentialBackoffRetry(1000, 3)); client.start();
这里的ExponentialBackoffRetry的含义是指数增长的重试间隔。根据这里的参数,第一次失败重试休息1000毫秒,第二次重试休息1000毫秒~3000毫秒,第三次失败重试休息1000毫秒~7000毫秒。这样指数增长。
PathChildrenCache cache = new PathChildrenCache(client, "/test", true);
cache.start(); cache.getListenable().addListener(new MyListener(observer));
这样就可以监听test节点下的所有节点了。
实现事件处理,只需实现PathChildrenCacheListener接口即可,示例如下。
public class MyListener implements PathChildrenCacheListener {
@Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: { // 新的节点创建了 ... break; } case CHILD_UPDATED: { // 节点数据更新了 ... break; } case CHILD_REMOVED: { // 节点删掉了 ... break; } } } }
转载地址:http://nvyub.baihongyu.com/