Zookeeper开源客户端框架Curator简介与示例

简介

        Curator最初由Netflix的Jordan Zimmerman开发, Curator提供了一套Java类库, 可以更容易的使用ZooKeeper.

        所谓ZooKeeper技巧(ZooKeeper Recipes),也可以称之为解决方案, 或者叫实现方案, 是指ZooKeeper的使用方法, 比如分布式的配置管理, Leader选举等

        Curator作为Apache ZooKeeper天生配套的组件。ZooKeeper的Java开发者自然而然的会选择它在项目中使用。

        官网链接:http://curator.apache.org/

提供的功能组件

  1. Framework 提供了一套高级的API, 简化了ZooKeeper的操作。 它增加了很多使用ZooKeeper开发的特性,可以处理ZooKeeper集群复杂的连接管理和重试机制
  2. Client 是ZooKeeper客户端的一个替代品, 提供了一些底层处理和相关的工具方法
  3. Recipes 实现了通用ZooKeeper的recipe, 该组件建立在Framework的基础之上
  4. Utilities 各种工具类
  5. Errors 异常处理, 连接, 恢复等.
  6. Extensions curator-recipes包实现了通用的技巧,这些技巧在ZooKeeper文档中有介绍。为了避免是这个包(package)变得巨大, recipes/applications将会放入一个独立的extension包下。并使用命名规则curator-x-name.

        Curator 编译好的类库被发布到Maven Center中。Curator包含几个artifact. 你可以根据你的需要在你的项目中加入相应的依赖。对于大多数开发者来说,引入curator-recipes这一个就足够了

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.6.0</version>
</dependency> 
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-client</artifactId>
    <version>2.6.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>2.6.0</version>
</dependency>

代码示例

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.api.GetChildrenBuilder;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;

import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * DateTime: 2015年1月9日 上午9:14:08
 *
 */
public class CuratorTest {
    private static String zkAddress = "hadoop02:2181,hadoop03:2181,hadoop04:2181";

    public static void main(String[] args) throws Exception {
        CuratorUtil curator = new CuratorUtil(zkAddress);
        curator.createNode("/zkroot/test1", "你好abc11");
        curator.createNode("/zkroot/test2", "你好abc22");
        curator.updateNode("/zkroot/test2", "你好abc22");
        List<String> list = curator.listChildren("/zkroot");
        Map<String, String> map = curator.listChildrenDetail("/zkroot");
        // curator.deleteNode("/zkroot");
        // curator.destory();
        System.out.println("=========================================");
        for (String str : list) {
            System.out.println(str);
        }

        System.out.println("=========================================");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "=>" + entry.getValue());
        }

        // 增加监听
        curator.addWatch("/zkroot", false);

        TimeUnit.SECONDS.sleep(600);
    }

}

class CuratorUtil {
    private CuratorFramework client;

    public CuratorUtil(String zkAddress) {
        client = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(1000, 3));
        client.getCuratorListenable().addListener(new NodeEventListener());
        client.start();
    }

    /**
     * 创建node
     * 
     * @param nodeName
     * @param value
     * @return
     */
    public boolean createNode(String nodeName, String value) {
        boolean suc = false;
        try {
            Stat stat = getClient().checkExists().forPath(nodeName);
            if (stat == null) {
                String opResult = null;
                if (Strings.isNullOrEmpty(value)) {
                    opResult = getClient().create().creatingParentsIfNeeded().forPath(nodeName);
                }
                else {
                    opResult =
                            getClient().create().creatingParentsIfNeeded()
                                .forPath(nodeName, value.getBytes(Charsets.UTF_8));
                }
                suc = Objects.equal(nodeName, opResult);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return suc;
    }

    /**
     * 更新节点
     * 
     * @param nodeName
     * @param value
     * @return
     */
    public boolean updateNode(String nodeName, String value) {
        boolean suc = false;
        try {
            Stat stat = getClient().checkExists().forPath(nodeName);
            if (stat != null) {
                Stat opResult = getClient().setData().forPath(nodeName, value.getBytes(Charsets.UTF_8));
                suc = opResult != null;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return suc;
    }

    /**
     * 删除节点
     * 
     * @param nodeName
     */
    public void deleteNode(String nodeName) {
        try {
            getClient().delete().deletingChildrenIfNeeded().forPath(nodeName);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 找到指定节点下所有子节点的名称与值
     * 
     * @param node
     * @return
     */
    public Map<String, String> listChildrenDetail(String node) {
        Map<String, String> map = Maps.newHashMap();
        try {
            GetChildrenBuilder childrenBuilder = getClient().getChildren();
            List<String> children = childrenBuilder.forPath(node);
            GetDataBuilder dataBuilder = getClient().getData();
            if (children != null) {
                for (String child : children) {
                    String propPath = ZKPaths.makePath(node, child);
                    map.put(child, new String(dataBuilder.forPath(propPath), Charsets.UTF_8));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 列出子节点的名称
     * 
     * @param node
     * @return
     */
    public List<String> listChildren(String node) {
        List<String> children = Lists.newArrayList();
        try {
            GetChildrenBuilder childrenBuilder = getClient().getChildren();
            children = childrenBuilder.forPath(node);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return children;
    }

    /**
     * 增加监听
     * 
     * @param node
     * @param isSelf
     *            true 为node本身增加监听 false 为node的子节点增加监听
     * @throws Exception
     */
    public void addWatch(String node, boolean isSelf) throws Exception {
        if (isSelf) {
            getClient().getData().watched().forPath(node);
        }
        else {
            getClient().getChildren().watched().forPath(node);
        }
    }

    /**
     * 增加监听
     * 
     * @param node
     * @param isSelf
     *            true 为node本身增加监听 false 为node的子节点增加监听
     * @param watcher
     * @throws Exception
     */
    public void addWatch(String node, boolean isSelf, Watcher watcher) throws Exception {
        if (isSelf) {
            getClient().getData().usingWatcher(watcher).forPath(node);
        }
        else {
            getClient().getChildren().usingWatcher(watcher).forPath(node);
        }
    }

    /**
     * 增加监听
     * 
     * @param node
     * @param isSelf
     *            true 为node本身增加监听 false 为node的子节点增加监听
     * @param watcher
     * @throws Exception
     */
    public void addWatch(String node, boolean isSelf, CuratorWatcher watcher) throws Exception {
        if (isSelf) {
            getClient().getData().usingWatcher(watcher).forPath(node);
        }
        else {
            getClient().getChildren().usingWatcher(watcher).forPath(node);
        }
    }

    /**
     * 销毁资源
     */
    public void destory() {
        if (client != null) {
            client.close();
        }
    }

    /**
     * 获取client
     * 
     * @return
     */
    public CuratorFramework getClient() {
        return client;
    }

}

// 监听器
final class NodeEventListener implements CuratorListener {
    @Override
    public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
        System.out.println(event.toString() + ".......................");
        final WatchedEvent watchedEvent = event.getWatchedEvent();
        if (watchedEvent != null) {
            System.out.println(watchedEvent.getState() + "=======================" + watchedEvent.getType());
            if (watchedEvent.getState() == KeeperState.SyncConnected) {
                switch (watchedEvent.getType()) {
                case NodeChildrenChanged:
                    // TODO
                    break;
                case NodeDataChanged:
                    // TODO
                    break;
                default:
                    break;
                }
            }
        }
    }
时间: 2024-08-03 15:58:44

Zookeeper开源客户端框架Curator简介与示例的相关文章

七:zooKeeper开源客户端ZkClient的api测试

ZkClient是Gitthub上一个开源的ZooKeeper客户端.ZKClient在ZooKeeper原生API接口之上进行了包装,是一个更加易用的ZooKeeper客户端.同时ZKClient在内部实现诸如Session超时重连,Watcher反复注册等功能. 一:maven依赖 1 <dependency> 2 <groupId>org.apache.zookeeper</groupId> 3 <artifactId>zookeeper</ar

4款开源云计算框架和工具简介

本文讲的是4款开源云计算框架和工具简介,[IT168 资讯]1.Enomalism (http://www.enomaly.com/) 云计算平台.Enomalism 是一个开放源代码项目,它提供了一个功能类似于 EC2 的云计算框架.Enomalism 基于 Linux,同时支持 Xen 和 Kernel Virtual Machine(KVM).Enomalism 提供了一个基于 TurboGears Web 应用程序框架和 Python 的软件栈. 2.Euclyptus (http://

结合BeautyEye开源UI框架实现的较美观的Java桌面程序

BeautyJavaSwingRobot 结合BeautyEye开源UI框架实现的较美观的Java桌面程序,主要功能就是图灵机器人和一个2345网站万年历的抓取.... 挺简单而且实用的一个项目,实现出来的效果也还不错.希望可以学到知识的小可爱不对应该是帅哥,可以给我star...共勉 , github(gayhub更准确?)项目地址 https://github.com/Snailclimb/BeautyJavaSwingRobot 1,效果图: 主要界面图 机器人效果图 身份证查询效果图 2

跨平台的WebRTC客户端框架:OpenWebRTC

Webrtc的ios框架编译 http://www.th7.cn/Program/IOS/201502/390418.shtml     WebRTC in WebKit : http://www.webrtcinwebkit.org/       OpenWebRTC was designed for flexibility and modularity. The bulk of the API layer is implemented in JavaScript, making it sup

DWZ-RIA v1.2 Final发布 DWZ富客户端框架

DWZ富客户端框架(jQuery RIA framework), 是中国人自己开发的基于jQuery实现的Ajax RIA开源框架. DWZ富客户端框架设计目标是简单实用.扩展方便.快速开发.RIA思路.轻量级DWZ支持用html扩展的方式来代替javascript代码, 基本可以保证程序员不董javascript, 也能使用各种页面组件和ajax技术. 如果有特定需求也可以扩展DWZ做定制化开化. 国内很多程序员javascript不熟, 大大影响了http://www.aliyun.com/

DWZ富客户端框架(jQuery RIA framework)

问题描述 项目介绍:DWZ富客户端框架(jQuery RIA framework), 是中国人自己开发的基于jQuery实现的Ajax RIA开源框架.DWZ富客户端框架设计目标是**简单实用.扩展方便.快速开发.RIA思路.轻量级**DWZ支持用html扩展的方式来代替javascript代码, 基本可以保证程序员不董javascript, 也能使用各种页面组件和ajax技术. 如果有特定需求也可以扩展DWZ做定制化开化.国内很多程序员javascript不熟, 大大影响了开发速度. 使用DW

JAVA 开源缓存框架

  JBossCache/TreeCache  JBossCache是一个复制的事务处理缓存,它允许你缓存企业级应用数据来更好的改善性能.缓存数据被自动复制,让你轻松进行Jboss服务器之间的集群工作.JBossCache能够通过Jboss应用服务或其他J2EE容器来运行一个Mbean服务,当然,它也能独立运行. JBossCache包括两个模块:TreeCache和TreeCacheAOP. TreeCache --是一个树形结构复制的事务处理缓存. TreeCacheAOP --是一个"面向

最牛逼的开源机器学习框架,你知道几个

文章讲的是最牛逼的开源机器学习框架,你知道几个,机器学习毫无疑问是当今最热的话题,它已经渗透到生活的方方面面,在移动互联网中混不懂点机器学习都不好意思,说几个能看的到的,经常用邮箱吧,是不是感觉垃圾邮件比N年前变少了,无聊了和siri聊过天不,想坐一下无人驾驶汽车吗,手累了用脸解个锁,智能化产品推荐是不是让你更懒了.看不到的就更多了:信用卡欺诈监测保证你的交易安全,股票交易/量化投资(知道你的高收益理财怎么来的吗?),手势识别(用过海豚浏览器的手势吗),还有医学分析等等,巨头们为了在未来占领先机

java jodd框架介绍及使用示例

Jodd是一个普通开源Java包.你可以把Jodd想象成Java的"瑞士军刀",不仅小,锋利而且包含许多便利的功能.Jodd 提供的功能有: 提供操作Java bean, 可以从各种数据源加载Bean, 简化JDBC的接连与代码, 剖析SQL查询, 处理时间与日期, 操作与格式化String, 搜索本地硬盘上的文件, 帮助处理Servlet请求等.除此之外还包含一个很小,但实用的基于JSP的MVC框架.   jodd使用示例: JODD中的时间操作类 jodd时间操作 1 import