---
title: "Zookeeper基础知识学习"
author: "艾伦蓝"
date: "2017-03-27T10:26:07Z"
tags: []
categories: ["编程语言"]
slug: "zookeeper"
draft: true
lastmod: "2017-03-27T10:48:14Z"
id: 2365944
url: "https://forlan.iteye.com/blog/2365944"
---

**简介**

<span style="color:red">**ZooKeeper是Hadoop的正式子项目，它是一个针对大型分布式系统的可靠协调系统**</span>，提供的功能包括：<span style="color:blue">**配置维护**</span>、<span style="color:red">**命名服务**</span>、<span style="color:darkred">分布式同步</span>、<span style="color:orange">组服务</span>等。**ZooKeeper的目标就是封装好复杂易出错的关键服务，将简单易用的接口和性能高效、功能稳定的系统提供给用户。**
Zookeeper是Google的Chubby一个开源的实现，<span style="color:red">**是高有效和可靠的协同工作系统**</span>，Zookeeper能够用来leader选举，配置信息维护等，<span style="color:red">**在一个分布式的环境中，需要一个Master实例或存储一些配置信息，确保文件写入的一致性等。**</span>
<span style="color:red">**ZooKeeper是一个分布式的，开放源码的分布式应用程序协调服务**</span>，包含一个简单的原语集，是Hadoop和Hbase的重要组件。 提供Java和C的接口。

Zookeeper 作为一个分布式的服务框架，**主要用来解决分布式集群中应用系统的一致性问题**，它能提供基于类似于文件系统的目录节点树方式的数据存储，<span style="color:red">**但是 Zookeeper 并不是用来专门存储数据的，它的作用主要是用来维护和监控你存储的数据的状态变化。**</span>通过监控这些数据状态的变化，从而可以达到基于数据的集群管理。

**原理**

<span style="color:red">**ZooKeeper是以Fast Paxos算法为基础的**</span>，paxos算法存在活锁的问题，即当有多个proposer交错提交时，有可能互相排斥导致没有一个proposer能提交成功，而Fast Paxos作了一些优化，**通过选举产生一个leader，只有leader才能提交propose**，具体算法可见Fast Paxos。因此，**要想弄懂ZooKeeper首先得对Fast Paxos有所了解。**
**ZooKeeper的基本运转流程：**
<span style="color:red">**1、选举Leader。**</span>
2、同步数据。
3、选举Leader过程中算法有很多，但要达到的选举标准是一致的。
<span style="color:red">**4、Leader要具有最高的zxid。**</span>
5、集群中大多数的机器得到响应并follow选出的Leader。

ZooKeeper代码版本中，提供了分布式独享锁、选举、队列的接口，代码在zookeeper-3.4.3\src\recipes。其中分布锁和队列有Java和C两个版本，选举只有Java版本

**统一命名空间**
在zookeeper中实现了一个类似file system系统的数据结构，比如/zookeeper/status。 每个节点都对应于一个znode节点。
znode节点的数据结构模型：

![](http://dl2.iteye.com/upload/attachment/0123/9428/1140b236-dbf6-32ef-96c3-4a250e2c1e2e.jpg)

<span style="color:red">**znode的数据结构内容：**</span>
 
**czxid**
The zxid of the change that caused this znode to be created.
**mzxid**
The zxid of the change that last modified this znode.
**ctime**
The time in milliseconds from epoch when this znode was created.
**mtime**
The time in milliseconds from epoch when this znode was last modified.
**version**
The number of changes to the data of this znode.
**cversion**
The number of changes to the children of this znode.
**aversion**
The number of changes to the ACL of this znode.
**ephemeralOwner**
The session id of the owner of this znode if the znode is an ephemeral node. If it is not an ephemeral node, it will be zero.
**dataLength**
The length of the data field of this znode.
**numChildren**
The number of children of this znode.
 
说明：　zxid (ZooKeeper Transaction Id，每次请求对应一个唯一的zxid，如果zxid a < zxid b ，则可以保证a一定发生在b之前)。

**配置推送(Watcher)**
<span style="color:red">**zookeeper为解决数据的一致性，使用了Watcher的异步回调接口，将服务端znode的变化以事件的形式通知给客户端，主要是一种反向推送的机制，让客户端可以做出及时响应。**</span>比如及时更新后端的可用集群服务列表。