ZooKeeper分步式集群安装及java编程命令操作

本文详细介绍了ZooKeeper的安装过程,包括单节点安装和分布式集群安装,并探讨了Zookeeper作为分布式协调服务的角色。此外,还涵盖了Zookeeper的命令行操作以及如何使用Java API进行操作。
摘要由CSDN通过智能技术生成

目录
zookeeper介绍
zookeeper单节点安装
zookeeper分布式集群安装
zookeeper命令行操作
Java编程现实命令行操作

  1. zookeeper介绍zookeeper是一个为分布式应用所设计的分布的、开源的协调服务,它主要是用来解决分布式应用中经常遇到的一些数据管理问题,简化分布式应用协调及其管理的难度,提供高性能的分布式服务。zookeeper本身可以以Standalone模式安装运行,不过它的长处在于通过分布式zookeeper集群(一个Leader,多个Follower),基于一定的策略来保证zookeeper集群的稳定性和可用性,从而实现分布式应用的可靠性。
    zookeeper是作为分布式协调服务,是不需要依赖于Hadoop的环境,也可以为其他的分布式环境提供服务
  2. zookeeper单节点安装Standalones模式系统环境:
[xulu@SZB-L0032014 ~]$ uname -a
Linux SZB-L0032014 2.6.32-573.el6.x86_64 #1 SMP Thu Jul 23 15:44:03 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[xulu@SZB-L0032014 ~]$ cat /etc/issue
CentOS release 6.7 (Final)
Kernel \r on an \m
[xulu@SZB-L0032014 ~]$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (rhel-2.5.5.4.el6-x86_64 u79-b14)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
[xulu@SZB-L0032014 ~]$

zookeepr解压目录结构

[xulu@SZB-L0032014 zookeeper-3.4.6]$ ll
total 1505
drwxr-xr-x  2 xulu xulu    1024 Feb 20  2014 bin
-rw-rw-r--  1 xulu xulu  82446 Feb 20  2014 build.xml
-rw-rw-r--  1 xulu xulu  80776 Feb 20  2014 CHANGES.txt
drwxr-xr-x  2 xulu xulu    1024 Feb 20  2014 conf
drwxr-xr-x 10 xulu xulu    1024 Feb 20  2014 contrib
drwxr-xr-x  2 xulu xulu    1024 Feb 20  2014 dist-maven
drwxr-xr-x  6 xulu xulu    3072 Feb 20  2014 docs
-rw-rw-r--  1 xulu xulu    1953 Feb 20  2014 ivysettings.xml
-rw-rw-r--  1 xulu xulu    3375 Feb 20  2014 ivy.xml
drwxr-xr-x  4 xulu xulu    1024 Feb 20  2014 lib
-rw-rw-r--  1 xulu xulu  11358 Feb 20  2014 LICENSE.txt
-rw-rw-r--  1 xulu xulu    170 Feb 20  2014 NOTICE.txt
-rw-rw-r--  1 xulu xulu    1770 Feb 20  2014 README_packaging.txt
-rw-rw-r--  1 xulu xulu    1585 Feb 20  2014 README.txt
drwxr-xr-x  5 xulu xulu    1024 Feb 20  2014 recipes
drwxr-xr-x  8 xulu xulu    1024 Feb 20  2014 src
-rw-rw-r--  1 xulu xulu 1340305 Feb 20  2014 zookeeper-3.4.6.jar
-rw-rw-r--  1 xulu xulu    836 Feb 20  2014 zookeeper-3.4.6.jar.asc
-rw-rw-r--  1 xulu xulu      33 Feb 20  2014 zookeeper-3.4.6.jar.md5
-rw-rw-r--  1 xulu xulu      41 Feb 20  2014 zookeeper-3.4.6.jar.sha1

在conf目录下面创建一个zoo.cfg的文件,并且修改配置参数

[xulu@SZB-L0032014 conf]$ cp zoo_sample.cfg zoo.cfg
[xulu@SZB-L0032014 conf]$ cat zoo.cfg 
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/home/xulu/zookeeper
# the port at which the clients will connect
clientPort=3181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

启动zookeeper服务

[xulu@SZB-L0032014 zookeeper-3.4.6]$ cd bin/
[xulu@SZB-L0032014 bin]$ ./zkServer.sh
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Usage: ./zkServer.sh {start|start-foreground|stop|restart|status|upgrade|print-cmd}
[xulu@SZB-L0032014 bin]$ ./zkServer.sh start
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
[xulu@SZB-L0032014 bin]$ jps
22140 Jps
22096 QuorumPeerMain
[xulu@SZB-L0032014 bin]$ ./zkServer.sh status
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: standalone
[xulu@SZB-L0032014 bin]$

分布式集群的搭建 准备3台机器
10.20.24.231 SZB-L0032014
10.20.25.199 SZB-L0032015
10.20.25.241 SZB-L0032016

在数据文件目录下面增加一个文件myid

[xulu@SZB-L0032014 zookeeper]$ cat myid
1
[xulu@SZB-L0032014 zookeeper]$
[xulu@SZB-L0032015 zookeeper]$ cat myid
2
[xulu@SZB-L0032015 zookeeper]$
[xulu@SZB-L0032016 zookeeper]$ cat myid
3
[xulu@SZB-L0032016 zookeeper]$

分别修改配置文件
修改:dataDir,clientPort
增加:集群的实例,server.X,”X”表示每个目录中的myid的值

[xulu@SZB-L0032014 conf]$ cat zoo.cfg 
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/home/xulu/zookeeper
# the port at which the clients will connect
clientPort=3181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

server.1=10.20.24.231:4888:5888
server.2=10.20.25.199:4889:5889
server.3=10.20.25.241:4890:5890

[xulu@SZB-L0032015 conf]$ cat zoo.cfg 
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/home/xulu/zookeeper
# the port at which the clients will connect
clientPort=3181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
server.1=10.20.24.231:4888:5888
server.2=10.20.25.199:4889:5889
server.3=10.20.25.241:4890:5890

[xulu@SZB-L0032016 conf]$ cat zoo.cfg 
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/home/xulu/zookeeper
# the port at which the clients will connect
clientPort=3181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

server.1=10.20.24.231:4888:5888
server.2=10.20.25.199:4889:5889
server.3=10.20.25.241:4890:5890

查看节点状态

[xulu@SZB-L0032015 bin]$ ./zkServer.sh status
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: follower
[xulu@SZB-L0032015 bin]$ 

[xulu@SZB-L0032016 bin]$ ./zkServer.sh status
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: leader
[xulu@SZB-L0032016 bin]$ 

[xulu@SZB-L0032014 bin]$ ./zkServer.sh status
JMX enabled by default
Using config: /home/xulu/zookeeper-3.4.6/bin/../conf/zoo.cfg
Mode: follower

4. zookeeper命令行操作
我们通过客户端连接ZooKeeper的集群,我们可以任意的zookeeper是进行连接。

[xulu@SZB-L0032016 bin]$ ./zkCli.sh -server 10.20.25.199:2181
Connecting to 10.20.25.199:2181
2016-11-21 16:28:18,935 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2016-11-21 16:28:18,938 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=SZB-L0032016
2016-11-21 16:28:18,939 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.7.0_79
2016-11-21 16:28:18,941 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2016-11-21 16:28:18,941 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=/opt/jdk1.7.0_79/jre
2016-11-21 16:28:18,941 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=/home/xulu/zookeeper-3.4.6/bin/../build/classes:/home/xulu/zookeeper-3.4.6/bin/../build/lib/*.jar:/home/xulu/zookeeper-3.4.6/bin/../lib/slf4j-log4j12-1.6.1.jar:/home/xulu/zookeeper-3.4.6/bin/../lib/slf4j-api-1.6.1.jar:/home/xulu/zookeeper-3.4.6/bin/../lib/netty-3.7.0.Final.jar:/home/xulu/zookeeper-3.4.6/bin/../lib/log4j-1.2.16.jar:/home/xulu/zookeeper-3.4.6/bin/../lib/jline-0.9.94.jar:/home/xulu/zookeeper-3.4.6/bin/../zookeeper-3.4.6.jar:/home/xulu/zookeeper-3.4.6/bin/../src/java/lib/*.jar:/home/xulu/zookeeper-3.4.6/bin/../conf:
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=/tmp
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Linux
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=2.6.32-573.el6.x86_64
2016-11-21 16:28:18,942 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=xulu
2016-11-21 16:28:18,943 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=/home/xulu
2016-11-21 16:28:18,943 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=/home/xulu/zookeeper-3.4.6/bin
2016-11-21 16:28:18,944 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=10.20.25.199:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@63f78dde
Welcome to ZooKeeper!
2016-11-21 16:28:18,975 [myid:] - INFO  [main-SendThread(10.20.25.199:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 10.20.25.199/10.20.25.199:2181. Will not attempt to authenticate using SASL (unknown error)
2016-11-21 16:28:18,981 [myid:] - INFO  [main-SendThread(10.20.25.199:2181):ClientCnxn$SendThread@852] - Socket connection established to 10.20.25.199/10.20.25.199:2181, initiating session
JLine support is enabled
2016-11-21 16:28:18,996 [myid:] - INFO  [main-SendThread(10.20.25.199:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 10.20.25.199/10.20.25.199:2181, sessionid = 0x15823a399d97d7f, negotiated timeout = 30000

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
[zk: 10.20.25.199:2181(CONNECTED) 0] 

集群已连接,下面我们要使用一下,ZooKeeper的命令行操作。
命令行操作
通过help打印命令行帮助

[zk: 10.20.25.199:2181(CONNECTED) 0] help
ZooKeeper -server host:port cmd args
        connect host:port
        get path [watch]
        ls path [watch]
        set path data [version]
        rmr path
        delquota [-n|-b] path
        quit 
        printwatches on|off
        create [-s] [-e] path data acl
        stat path [watch]
        close 
        ls2 path [watch]
        history 
        listquota path
        setAcl path acl
        getAcl path
        sync path
        redo cmdno
        addauth scheme auth
        delete path [version]
        setquota -n|-b val path
[zk: 10.20.25.199:2181(CONNECTED) 1] 

ZooKeeper的结构,很像是目录结构,我们看到了像ls这样熟悉的命令。

#ls,查看/目录内容
[zk: 10.20.25.199:2181(CONNECTED) 1] ls /
[hive_zookeeper_namespace_hive, drill, hbase, zookeeper]

#create,创建一个node节点
[zk: 10.20.25.199:2181(CONNECTED) 2] create /node xlucas
Created /node
#ls,再查看/目录
[zk: 10.20.25.199:2181(CONNECTED) 3] ls /
[hive_zookeeper_namespace_hive, drill, node, hbase, zookeeper]

#get,查看/node的数据信息
[zk: 10.20.25.199:2181(CONNECTED) 4] get /node
xlucas
cZxid = 0x180009d98e
ctime = Mon Nov 21 16:45:13 CST 2016
mZxid = 0x180009d98e
mtime = Mon Nov 21 16:45:13 CST 2016
pZxid = 0x180009d98e
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 6
numChildren = 0

#set,修改数据
[zk: 10.20.25.199:2181(CONNECTED) 5] set /node www.xlucas.com
cZxid = 0x180009d98e
ctime = Mon Nov 21 16:45:13 CST 2016
mZxid = 0x180009d9a7
mtime = Mon Nov 21 16:46:22 CST 2016
pZxid = 0x180009d98e
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 14
numChildren = 0

#get,再查看/node的数据信息,已改为www.xlucas.com
[zk: 10.20.25.199:2181(CONNECTED) 6] get /node               
www.xlucas.com
cZxid = 0x180009d98e
ctime = Mon Nov 21 16:45:13 CST 2016
mZxid = 0x180009d9a7
mtime = Mon Nov 21 16:46:22 CST 2016
pZxid = 0x180009d98e
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 14
numChildren = 0

#delete,删除/node
[zk: 10.20.25.199:2181(CONNECTED) 7] delete /node
[zk: 10.20.25.199:2181(CONNECTED) 8] ls /
[hive_zookeeper_namespace_hive, drill, hbase, zookeeper]
[zk: 10.20.25.199:2181(CONNECTED) 9] 

#quit,退出客户端连接
[zk: 10.20.25.199:2181(CONNECTED) 9] quit
Quitting...
2016-11-21 16:48:46,512 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x15823a399d97d7f closed
2016-11-21 16:48:46,512 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

java操作zookeeper API

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperDemo {

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        // 创建一个与服务器的连接
        // TODO Auto-generated method stub
        ZooKeeper zk=new ZooKeeper("10.20.25.199:2181", 6000, new Watcher(){
            // 监控所有被触发的事件
            @Override
            public void process(WatchedEvent event) {
                System.out.println("EVENT:" + event.getType());             
            }

        });
          // 查看根节点
        System.out.println("ls / "+zk.getChildren("/", true));

        // 创建一个目录节点
        if(zk.exists("/node", true)==null){
            zk.create("/node", "xlucas".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("create /node xlucas");
            System.out.println("get /node data"+new String(zk.getData("/node", false, null)));
            System.out.println("ls / "+zk.getChildren("/", true));
        }

        // 创建一个子目录节点
            if (zk.exists("/node/sub1", true) == null) {
                zk.create("/node/sub1", "sub1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println("create /node/sub1 sub1");

                System.out.println("ls /node => " + zk.getChildren("/node", true));
            }

        // 修改节点数据
            if (zk.exists("/node", true) != null) {
                zk.setData("/node", "changed".getBytes(), -1);

                System.out.println("get /node => " + new String(zk.getData("/node", false, null)));
            }

        // 删除节点
            if (zk.exists("/node/sub1", true) != null) {
                zk.delete("/node/sub1", -1);
                zk.delete("/node", -1);

                System.out.println("ls / => " + zk.getChildren("/", true));
            }

          // 关闭连接
            zk.close();

    }

}

编译

[xulu@SZB-L0032015 ~]$ javac -cp .:./zookeeper-3.4.6/* ZookeeperDemo.java 

运行

[xulu@SZB-L0032015 ~]$ java -cp .:./zookeeper-3.4.6/*:./zookeeper-3.4.6/lib/* ZookeeperDemo 
log4j:WARN No appenders could be found for logger (org.apache.zookeeper.ZooKeeper).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
EVENT:None
ls / [hive_zookeeper_namespace_hive, drill, hbase, zookeeper]
EVENT:NodeCreated
EVENT:NodeChildrenChanged
create /node xlucas
get /node dataxlucas
ls / [hive_zookeeper_namespace_hive, drill, node, hbase, zookeeper]
EVENT:NodeCreated
create /node/sub1 sub1
ls /node => [sub1]
EVENT:NodeDataChanged
get /node => changed
EVENT:NodeDeleted
EVENT:NodeChildrenChanged
EVENT:NodeChildrenChanged
ls / => [hive_zookeeper_namespace_hive, drill, hbase, zookeeper]
[xulu@SZB-L0032015 ~]$ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值