ZooKeeper架构篇 - 认识ZooKeeper


一、什么是ZooKeeper?

ZooKeeper是一个开源的致力于分布式协调服务的服务器。

Apache ZooKeeper is an effort to develop and maintain an open-source server which enables highly reliable distributed coordination.

ZooKeeper为分布式应用提供了配置信息管理、命名服务、分布式锁等基础服务。在解决分布式数据一致性方面,并没有直接采用Paxos算法,而是采用ZAB(ZooKeeper Atomic Broadcast)的分布式数据一致性协议。

ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications. Each time they are implemented there is a lot of work that goes into fixing the bugs and race conditions that are inevitable. Because of the difficulty of implementing these kinds of services, applications initially usually skimp on them, which make them brittle in the presence of change and difficult to manage. Even when done correctly, different implementations of these services lead to management complexity when the applications are deployed.


二、 一致性保证

ZooKeeper可以保证如下的分布式一致性特性。

  • 顺序一致性。一个客户端发起的事务请求,按照发送的顺序应用到ZooKeeper中。
  • 原子性。事务请求在整个集群的应用情况都是相同的,要么成功应用,要么没有应用。
  • 单一系统视图。无论客户端连接的是哪个ZooKeeper服务器,其看到的服务端数据模型都是相同的。
  • 可靠性。一旦服务端成功应用了一个事务,并且完成了对客户端的响应。那么该事务所引起的服务器状态变更将会一直保留下来。
  • 实时性。保证在某一个时间段范围内,客户端能够从服务端读取最新的数据。
    在这里插入图片描述

三、 数据模型

ZooKeeper使用ZNode结构存储数据。

ZNode是ZooKeeper数据的最小单元,大小应该小于1MB。除了可以存储数据,还可以挂载子节点。

多个数据节点按照层次化结构进行组织,形成了树。

The ZooKeeper client and the server implementations have sanity checks to ensure that znodes have less than 1M of data, but the data should be much less than that on average.

在这里插入图片描述


节点特性

节点类型有:持久节点、临时节点、顺序节点、容器节点(3.5.3版本)、TTL节点(3.5.3版本)五种类型。

  • 持久节点:节点被创建之后,一直存储在ZooKeeper服务器上。
  • 临时节点:生命周期与客户端会话绑定在一起。如果客户端会话失效,而非TCP连接断开,该节点会被自动清理。临时节点不允许有子节点。
  • 顺序节点:具有顺序性。会在节点路径的末尾添加10位单调递增的数字。数字对于父节点来说是唯一的。
  • 容器节点:当容器中的所有子节点被删除后,该容器会在将来的某一时刻被删除。
  • TTL节点:对于持久节点、持久顺序节点,在指定时间内没有被修改并且没有子节点,该节点会在将来的某一时刻被删除。

五种类型的节点可以组合成多种类型的节点。

  • PERSISTENT
  • PERSISTENT_SEQUENTIAL
  • EPHEMERAL
  • EPHEMERAL_SEQUENTIAL
  • CONTAINER
  • PERSISTENT_WITH_TTL
  • PERSISTENT_SEQUENTIAL_WITH_TTL

状态信息

每个数据节点除了存储数据内容之外,还会存储节点本身的状态信息。

可以通过get或者stat命令获取节点的状态信息。(get命令额外输出节点的内容)

stat命令
get命令

  • czxid:节点被创建时的事务ID
  • mzxid:节点最近一次被修改时的事务ID
  • ctime:节点被创建的时间
  • mtime:节点最近一次被修改的时间
  • pzxid:子节点列表最近一次被修改时的事务ID
  • cversion:子节点的版本号
  • dataVersion:当前数据节点的版本号
  • aclVersion:当前节点的acl版本号
  • ephemeralOwner:创建临时节点的session id。如果是非临时节点,值为0
  • dataLength:数据内容的长度
  • numChildren:子节点的个数

四、服务器角色

服务器角色分为:Leader、Follower、Observer。

  • Leader

    事务请求的唯一调度者和处理者。保证集群事务处理的顺序性。
    集群内部各服务器的调度者。

  • Follower

    处理客户端的非事务请求,转发事务请求给Leader。
    参与事务请求Proposal的投票。
    参与Leader选举投票。

  • Observer

    处理客户端的非事务请求,转发事务请求给Leader。