欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Zookeeper入门 - Hello World.md 博客分类: Zookeeper zookeeperhelloworld例子demo 

程序员文章站 2024-03-18 16:00:40
...

 

 

示例将以单击模式最简化安装Zookeeper,并分别以ZK客户端和Java API编写 HelloWorld程序。

 

下载

当前最新: zookeeper-3.4.6.tar.gz
官网下载
我的备份

 

 

安装

 

tar zxvf zookeeper-3.4.6.tar.gz
cd zookeeper-3.4.6/
#zookeeper无需编译,直接解压就可使用
 

 

配置

 

#修改示例配置文件为指定的zoo.cfg
cd conf
cp zoo_sample.cfg zoo.cfg
#编辑zoo.cfg添加下行参数。其他参数稍后再配,本次只需要指定该zookeeper数据文件存放位置即可
dataDir=/var/tmp/zkdata

#创建该数据文件存放目录
mkdir -p /var/tmp/zkdata

#新建myid标识文件(集群模式中各个zk的身份证,先配着混个脸熟。)
cd /var/tmp/zkdata/
echo '1' > myid
 

 

启动

 

#回到zookeeper安装目录/bin 下,执行开启命令
 ./zkServer.sh start
#显示如下信息,表示开启正常
JMX enabled by default
Using config: /home/storm/zookeeper-3.4.6/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
 

 

检测

 

#Zookeeper维护通常为4个字母组成的常用命令,很酷炫的样子。
#本例使用ruok(Are you OK?)命令检测开启是否成功
echo ruok | nc localhost 2181
#正常情况下会返回 'imok' = I'm OK.
 

 

客户端

 

#使用zkCli.sh客户端(bin目录下)编写Helloworld
./zkCli.sh
[zk: localhost:2181(CONNECTED) 0] ls /
[zookeeper]
#注意开启zkCli.sh客户端后敲进去的命令是 ls /,因为根目录没有节点,所有返回为空
 
    命令简介:

[zk: localhost:2181(CONNECTED) 0] 即为客户端命令行,输入help可获取具体的命令解释。先预览下面三个简单命令:
1. ls path [watch] :同linux列出内容
2. get path [watch] : 获取znode值
3. set path data [version] : 设置znode值
4. create [-s] [-e] path data acl :

    使用示例:

 

[zk: localhost:2181(CONNECTED) 0] ls /
[zookeeper]
[zk: localhost:2181(CONNECTED) 2] create /mypath helloword
Created /mypath
[zk: localhost:2181(CONNECTED) 3] ls /
[mypath, zookeeper, futeng]
[zk: localhost:2181(CONNECTED) 4] get /mypath
helloword
cZxid = 0x4b
ctime = Wed May 21 00:19:07 CST 2014
mZxid = 0x4b
mtime = Wed May 21 00:19:07 CST 2014
pZxid = 0x4b
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 9
numChildren = 0
[zk: localhost:2181(CONNECTED) 5]

     仔细看 helloworld 在哪 :)

 

 

使用Java API 编写Helloworld

    普通Java工程引入zookeeper-3.4.6.jar包即可。
    Maven工程可添加如下依赖:

 

<dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
</dependency>

     创建连接Zookeeper类(该类代码摘自来自《Hadoop权威指南》)

 

 

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;

public class ConnectionWatcher implements Watcher {
    private CountDownLatch connectedSignal = new CountDownLatch(1);

    private static final int SESSION_TIMEOUT = 5000;

    ZooKeeper zk;

    public void connect(String hosts) throws InterruptedException, IOException {
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
        connectedSignal.await();
    }

    @Override
    public void process(WatchedEvent event) {
        if(event.getState() == KeeperState.SyncConnected) {
            connectedSignal.countDown();
        }
    }

    public void close() throws InterruptedException {
        zk.close();
    }
}

 

 

 

     创建新建节点和获取节点值类

 

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;

/**
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/

public class HelloZookeeper extends ConnectionWatcher{

    public void createNode(String nodeName, String nodeValue)
                                         throws KeeperException, InterruptedException {

        String path = "/" + nodeName;

        String createPath = zk.create(path, nodeValue.getBytes(),
                                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        System.out.println("Created znode:"+createPath);
    }

    public void getValue(String nodeName) throws KeeperException, InterruptedException {

        String path = "/" + nodeName;

        byte[] value = zk.getData(path, false, null);

        System.out.printf("[%s,%s]", path, new String(value));
    }

    public static void main(String[] args) throws Exception, IOException {
        // 1 - Connect
        JoinGroup joinGroup = new JoinGroup();
        joinGroup.connect("192.168.80.219");

        // 2 - Created node
        joinGroup.createNode("hello", "world");

        // 3- Get value
        joinGroup.getValue("hello");

        TimeUnit.HOURS.sleep(1);
    }
}

 

 

    执行显示如下

 

Created znode:/hello
[/hello,world]

 

 

    另外官网的zookeeper示例代码也很赞,已经附在文后。

 

     version1.0 first created 2014-05-20

     version2.0 删除无用shell显示,精简排版 2014-06-04

 

                                                                                                               转载请标明作者和原文链接

 

                                                                                                               ifuteng#gmail.com 2014/5/20