原创

Zookeeper总结笔记

温馨提示:
本文最后更新于 2018年01月03日,已超过 2,298 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

Zookeeper概述

Zookeeper官网

什么是Zookeeper?

ZooKeeper是一种集中式服务,用于维护配置信息,命名,提供分布式同步和提供组服务。所有这些类型的服务都以分布式应用程序的某种形式使用。每次实施它们都需要做很多工作来修复不可避免的错误和竞争条件。由于难以实现这些类型的服务,应用程序最初通常会吝啬它们,这使得它们在变化的情况下变得脆弱并且难以管理。即使正确完成,这些服务的不同实现也会在部署应用程序时导致管理复杂性。

Zookeeper的特点

  1. 一个领导者(Leader),多个跟随者(Follower)组成的集群。
  2. 集群中只要半数以上节点存活,Zookeeper集群就能正常服务。
  3. 全局数据一致:每个Server保存一份相同的数据副本,Client无论连接哪个Server,数据都是一致的。
  4. 更新请求顺序进行:来自同一个Client的更新请求按其发送顺序依次执行。
  5. 数据更新原子性:一次数据更新要么成功,要么失败。
  6. 实时性:在一定范围内,Client能读到最新数据。

Zookeeper数据结构

Zookeeper数据模型的结构与Unix文件系统很类似,整体上可以看作是一棵树,每个节点称作一个ZNode。每一个ZNode默认能存储1MB的数据,每个ZNode都可以通过其唯一路径唯一标识。

应用场景

提供的服务包括:统一命名服务、统一配置管理、统一集群管理、服务器节点动态上下线、软负载均衡等。

安装Zookeeper

1. 单机版

安装要点

#1.修改配置文件
mv zoo_sample.cfg zoo.cfg

#2.创建文件夹
mkdir -p /home/zookeeper/zkdata/

#3.打开zoo.cfg文件,修改dataDir路径
vi zoo.cfg
##修改为以下内容(自定义文件夹)
dataDir=/home/zookeeper/zkdata

#4.添加环境变量(/etc/profile)
#ZOOKEEPER
export ZOOKEEPER_HOME=/home/zookeeper/zookeeper-3.4.12
export PATH=$PATH:$ZOOKEEPER_HOME/bin

操作命令

  1. 启动Zookeeper:zkServer.sh start
  2. 查看进程是否启动:jps
  3. 查看状态:zkServer.sh status
  4. 启动客户端:zkCli.sh
  5. 退出客户端:quit
  6. 停止Zookeeper:zkServer.sh stop

zoo.cfg配置参数解读

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=/tmp/zookeeper
# 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
配置参数解读

Zookeeper中的配置文件zoo.cfg中参数含义解读如下:

  1. tickTime =2000:通信心跳数,Zookeeper服务器与客户端心跳时间,单位毫秒。Zookeeper使用的基本时间,服务器之间或客户端与服务器之间维持心跳的时间间隔,也就是每个tickTime时间就会发送一个心跳,时间单位为毫秒。它用于心跳机制,并且设置最小的session超时时间为两倍心跳时间。(session的最小超时时间是2*tickTime)。
  2. initLimit =10:LF初始通信时限。集群中的Follower跟随者服务器与Leader领导者服务器之间初始连接时能容忍的最多心跳数(tickTime的数量),用它来限定集群中的Zookeeper服务器连接到Leader的时限。
  3. syncLimit =5:LF同步通信时限。集群中Leader与Follower之间的最大响应时间单位,假如响应超过syncLimit * tickTime,Leader认为Follwer死掉,从服务器列表中删除Follwer。
  4. dataDir:数据文件目录+数据持久化路径。主要用于保存Zookeeper中的数据。
  5. clientPort =2181:客户端连接端口。监听客户端连接的端口。

2.集群模式

集群模式至少三台节点,为了节约成本,最好是奇数个。

安装要点:

我这里三台机器

#1.修改配置文件
mv zoo_sample.cfg zoo.cfg

#2.创建文件夹
mkdir -p /home/zookeeper/zkdata/

#3.在zkdata目录下创建一个myid文件
touch myid
vi myid

#4.打开zoo.cfg文件,修改dataDir路径,添加三台节点的信息。
vi zoo.cfg
##修改为以下内容(自定义文件夹)
dataDir=/home/zookeeper/zkdata
##############cluster##############
server.1=master:2888:3888
server.2=slave1:2888:3888
server.3=slave2:2888:3888


#5..添加环境变量(/etc/profile)
#ZOOKEEPER
export ZOOKEEPER_HOME=/home/zookeeper/zookeeper-3.4.12
export PATH=$PATH:$ZOOKEEPER_HOME/bin

#6.在master节点做好之后分发到其它两台节点
scp -r /home/zookeeper/ slave1:/home/
scp -r /home/zookeeper/ slave2:/home/
scp /etc/profile slave1:/etc/
scp /etc/profile slave2:/etc/

server参数解读

##############cluster##############
server.1=master:2888:3888
server.2=slave1:2888:3888
server.3=slave2:2888:3888

server.A=B:C:D

A是一个数字,表示这个是第几号服务器;

集群模式下配置一个文件myid,这个文件在dataDir目录下,这个文件里面有一个数据就是A的值,Zookeeper启动时读取此文件,拿到里面的数据与zoo.cfg里面的配置信息比较从而判断到底是哪个server。

B是这个服务器的ip地址;

C是这个服务器与集群中的Leader服务器交换信息的端口;

D是万一集群中的Leader服务器挂了,需要一个端口来重新进行选举,选出一个新的Leader,而这个端口就是用来执行选举时服务器相互通信的端口。

Zookeeper客户端操作命令

命令基本语法 功能描述
help 显示所有操作命令
ls path [watch] 使用 ls 命令来查看当前znode中所包含的内容
ls2 path [watch] 查看当前节点数据并能看到更新次数等数据
create 普通创建-s 含有序列-e 临时(重启或者超时消失)
get path [watch] 获得节点的值
set 设置节点的具体值
stat 查看节点状态
delete 删除节点
rmr 递归删除节点

Zookeeper内部原理

Zookeeper的选举机制

  1. 半数机制:集群中半数以上的机器存活,集群可用。所以Zookeeper适合安装奇数台服务器。
  2. Zookeeper虽然在配置文件中并没有指定Master和Slave。但是,Zookeeper工作时,是有一个节点为Leader,其他则为Follower,Leader是通过内部的选举机制临时产生的。

解读:

(1)服务器1启动,此时只有它一台服务器启动了,它发出去的报文没有任何响应,所以它的选举状态一直是LOOKING状态。

(2)服务器2启动,它与最开始启动的服务器1进行通信,互相交换自己的选举结果,由于两者都没有历史数据,所以id值较大的服务器2胜出,但是由于没有达到超过半数以上的服务器都同意选举它(这个例子中的半数以上是3),所以服务器1、2还是继续保持LOOKING状态。

(3)服务器3启动,根据前面的理论分析,服务器3成为服务器1、2、3中的老大,而与上面不同的是,此时有三台服务器选举了它,所以它成为了这次选举的Leader。

(4)服务器4启动,根据前面的分析,理论上服务器4应该是服务器1、2、3、4中最大的,但是由于前面已经有半数以上的服务器选举了服务器3,所以它只能接收当小弟的命了。

(5)服务器5启动,同4一样当小弟。

Zookeeper的监听原理

Zookeeper写数据流程

Zookeeper实战

创建/获取节点

package com.lzhpo.test1;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @Author:lzhpo
 */
public class Crud {

    private static String connectString = "192.168.200.140:2181,192.168.200.141:2181,192.168.200.142:2181";    //逗号后面不要跟空格!!!
    private static int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;

    @Before
    public void init() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                //收到时间之后的回调函数(用户的业务逻辑)
                System.out.println(watchedEvent.getType() + "---" + watchedEvent.getPath());
                //再次启动监听
                try {
                    zkClient.getChildren("/",true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 创建子节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void create() throws KeeperException, InterruptedException {
        /**
         * 参数1:要创建的节点的路径。
         * 参数2:节点数据。
         * 参数3:节点权限。
         * 参数4:节点类型。
         */
        String nodeCreated = zkClient.create(
                "/fruits",
                "orange".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT
        );
    }

    /**
     * 获取子节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/",true);
        children.forEach(s -> {
            System.out.println(s);
        });
    }

    /**
     * 判断Znode是否存在
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat stat = zkClient.exists("/lzhpo", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }
}

监听节点上下线

DistributeClient

package com.lzhpo.test2.server;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @Author:lzhpo
 */
public class DistributeClient {

    private static String connectString = "192.168.200.140:2181,192.168.200.141:2181,192.168.200.142:2181";    //逗号后面不要跟空格!!!
    private static int sessionTimeout = 2000;
    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    public static void main(String[] args) throws Exception {
        //1.获取zk连接
        DistributeClient client = new DistributeClient();
        client.getConnect();
        //2.获取servers的子节点信息,从中获取服务器信息列表
        client.getServerList();
        //3.业务进程启动
        client.business();
    }

    /**
     * 创建到zk的客户端连接
     * @throws IOException
     */
    public void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent event) {

                // 再次启动监听
                try {
                    getServerList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取服务器列表信息
     * @throws Exception
     */
    public void getServerList() throws Exception {

        // 1获取服务器子节点信息,并且对父节点进行监听
        List<String> children = zk.getChildren(parentNode, true);

        // 2存储服务器信息列表
        ArrayList<String> servers = new ArrayList<>();

        // 3遍历所有节点,获取节点中的主机名称信息
        for (String child : children) {
            byte[] data = zk.getData(parentNode + "/" + child, false, null);

            servers.add(new String(data));
        }

        // 4打印服务器列表信息
        System.out.println(servers);
    }

    /**
     * 业务功能
     * @throws Exception
     */
    public void business() throws Exception{

        System.out.println("client is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

}

DistributeServer

package com.lzhpo.test2.server;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * <p>Title:</p>
 * <p>Description:
 * 程序运行带参数,参数就是服务器的IP地址。
 * </p>
 *
 * @Author:lzhpo
 */
public class DistributeServer {

    private static String connectString = "192.168.200.140:2181,192.168.200.141:2181,192.168.200.142:2181";    //逗号后面不要跟空格!!!
    private static int sessionTimeout = 2000;
    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        //1.获取zk连接
        DistributeServer server = new DistributeServer();
        server.getConnect();
        //2.利用zk连接注册服务器信息
        server.registServer(args[0]);
        //3.启动业务功能
        server.business(args[0]);
    }

    /**
     * 创建到zk的客户端连接
     */
    private void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }

    /**
     * 注册服务器
     * @param hostname
     * @throws KeeperException
     * @throws InterruptedException
     */
    private void registServer(String hostname) throws KeeperException, InterruptedException {
        String create = zk.create(
                parentNode +
                        "/servers",
                hostname.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + "--->is online" + create);
    }

    /**
     * 业务功能
     * @param hostname
     * @throws InterruptedException
     */
    private void business(String hostname) throws InterruptedException {
        System.out.println(hostname + "--->is working...");
        Thread.sleep(Long.MAX_VALUE);
    }

}
本文目录