Zookeeper的使用入门介绍

一、Zookeeper下载地址https://www.apache.org/dyn/closer.cgi/zookeeper/

首先介绍一下,本人使用的是linux——3.4.13的zk

二、Zookeeper的简单实用以及api介绍

1.解压之后进入conf目录,复制一份zoo_sample.cfg并改名为zoo.cfg

cp zoo_sample.cfg zoo.cfg

2.查看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=/usr/local/zookeeper-3.4.13/data
# the port at which the clients will connect
clientPort=2181
# 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

在这先改一下dataDir的值,表示的是zk存放数据的目录

3.进入bin目录启动zk,注意,启动前要配置JAVA_HOME的环境变量

./zkServer.sh start

4.在bin目录下运行客户端

./zkCli.sh -server 127.0.0.1:2181

5.然后我们可以用help命令查看当前可以运行哪些指令:

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

其中get获取节点数据

       ls查看当前节点的子节点

       create创建节点

       delete删除节点

      set设置节点的内容数据

6.试用

ls   /                 查看根目录下的节点

create      /zk_test     aaa          在根目录下创建zk_test 节点,节点数据为aaa        

get        /zk_test              获取zk_test节点数据

set       /zk_test       bbb     给zk_test节点赋值,替换掉原来的aaa,改为bbb

三、使用Java操作Zookeeper

需要的jar包:slf4j-api-1.7.25.jar

                      zkclient-0.10.jar

                      zookeeper-3.4.13.jar

package com;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

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

/**
 * java操作zookeeper的demo
 */
public class ZKClient {

    //   zk地址
    private static final String CONNECT_ADDR = "192.168.126.131";

    //    超时时间  单位ms
    private static final int SESSION_OUTTIME = 2000;
    //信号量,程序阻塞执行,用于等待zk连接成功,发送成功信号
    private static final CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        /**
         * zk构造器参数解析:
         *      connectString 连接服务器列表
         *      sessionTimeout 心跳检测时间周期(ms)
         *      watcher 时间处理通知器
         *      canBeReadOnly 表示当前会话是否支持只读
         *      sessionId,sessionPasswd 提供链接zk的sessionId和密码,通过这两个确定唯一一台客户端,目的是可以提供重复会话
         *
         *  ***注意***:
         *  zk客户端与服务器端会话的建立是一个异步的过程也就是说在程序中,我们程序方法在处理完客户端初始化后,立即返回(程序往下执行代码,这样,大多数情况下我们并没有真正构建好一个可用会话,在会话的声明周期处于"CONNECTING"时才算真正建立完毕,所以我们需要使用多线程中的一个工具类)
         */
        ZooKeeper zk = new ZooKeeper(CONNECT_ADDR, SESSION_OUTTIME, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                //获取事件的状态
                KeeperState keeperState = event.getState();
                EventType eventType = event.getType();
                //如果是建立连接
                if (KeeperState.SyncConnected == keeperState) {
                    if (EventType.None == eventType) {
                        //如果建立连接成功,则发送信号量,让后续阻塞程序向下执行
                        System.out.println("zk 建立连接");
                        connectedSemaphore.countDown();
                    }
                }
            }
        });

//        进行阻塞,等待zk建立连接之后再向下执行
        connectedSemaphore.await();
        System.out.println("  ..  ");
        //创建节点
        /**
         * 参数一:节点名称    不允许递归创建节点,只能一级级的创建
         * 参数二:节点数据    节点类型是字节数组(不支持序列化方式,如果需要实现序列化,可使用java相关的序列化框架)
         * 参数三:节点权限    使用Ids.OPEN_ACL_UNSAFE开发权限即可(一般在权限没有太高要求的场景下,没必要关注)
         * 参数四:节点类型    PERSISTENT (持久节点)
         *                 PERSISTENT_SEQUENTIAL(持久顺序节点)
         *                 EPHEMRAL(临时节点)
         *                  EPHEMRAL_SEQUENTIAL(临时顺序节点)
         *
         * 注意:不能重复创建持久节点  KeeperException$NodeExistsException
         */
//        zk.create("/zk_javatest", "javaapi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        //创建子节点
//        zk.create("/zk_javatest/children","children data".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

        //获取节点信息
//        byte[] data = zk.getData("/zk_javatest", false, null);
        //获取该节点数据
//        System.out.println(new String(data));
        //获取该节点的子节点【不能往下递归获取】
//        System.out.println(zk.getChildren("/zk_javatest",false));

        //修改节点的值
//        zk.setData("/zk_javatest", "zk_modified".getBytes(), -1);
//        byte[] data = zk.getData("/zk_javatest", false, null);
//        System.out.println(new String(data));

        //判断节点是否存在  返回值部位null就是存在该节点
//        System.out.println(zk.exists("/zk_javatest/children",false));
//        System.out.println(zk.exists("/zk_javatest/children2",false));
//        System.out.println(zk.exists("/zk_javatest/children3",false));

        //删除节点   如果删除不存在的节点会报错  KeeperException$NoNodeException
//        zk.delete("/zk_javatest/children2", -1);
        System.out.println(zk.exists("/zk_javatest/children2",false));

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

大家可以去dubbo官网去看下实例教程:如下

dubbo注册中心zokeeper安装实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值