ZooKeeper 教程

ZooKeeper 是什么、核心概念(znode / session / watcher )、单机安装、zkCli 命令、典型应用场景与集群选举概览。

Beginner
Key PointsZooKeeper 用一棵内存中的节点树(znode)把分布式系统的协调问题统一成「读/写/监听」三个动作。

ZooKeeper 是什么

ZooKeeper is an Apache distributed coordination service, originally built by Yahoo for Hadoop. It tackles the hardest, most error-prone problems in distributed systems: centralised config, service discovery, leader election, and cross-process locks.

It does not store business data; instead it holds an in-memory tree of nodes (znode tree) where coordination state lives. Clients read, write and watch this tree with simple primitives, then build config centres, registries and locks on top.

Text
         应用 A ─┐                         ┌─ 配置中心
         应用 B ─┼──▶  ZooKeeper  ◀──watch──┤
         应用 C ─┘   (znode 树 + Watcher)   └─ 选主 / 分布式锁

核心概念

znode 数据模型

Data is organised like a file system: hierarchical paths (e.g. /app/conf), where each path element is a znode. Unlike a file system, each znode can both hold children and store a small payload (default limit 1 MB; keep only coordination data, never bulk objects).

节点类型

类型特点典型用途
持久节点 PERSISTENT客户端断开后依然存在配置、元数据
临时节点 EPHEMERAL会话结束即删除,不能挂子节点选主、存活探测
顺序节点 SEQUENTIAL创建时追加单调递增序号分布式锁、公平队列
持久顺序 / 临时顺序上面两类与顺序标志组合锁、队列

Session 会话

A connection opens a session with a server-side timeout (e.g. 30s). As long as the client heartbeats within the timeout the session stays alive; on timeout, all its ephemeral nodes are deleted automatically — the basis for using ephemerals as liveness markers.

Watcher 监视器

A Watcher is how ZooKeeper delivers notifications. When calling exists / getData / getChildren a client can register a one-shot Watcher: when that node is created, deleted or its data changes, the server pushes an event. Watchers are one-shot — re-register after each trigger to keep watching.

版本与 ACL

Each znode keeps three versions: dataVersion, cversion, aversion. Writes can carry a version for optimistic locking (rejected on mismatch, preventing concurrent overwrite). ACLs control access via schemes like world, auth, digest and ip.

单机安装与启动

After extracting the download, the key file is conf/zoo.cfg. A minimal working config only needs a data directory and a port:

PROPERTIES
# conf/zoo.cfg
tickTime=2000
dataDir=/var/lib/zookeeper
clientPort=2181
initLimit=5
syncLimit=2

Start the server (bin/zkServer.sh on Linux/macOS, bin/zkServer.cmd on Windows):

Shell
# 启动
bin/zkServer.sh start

# 查看状态
bin/zkServer.sh status
Output
ZooKeeper JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED

Mode: standalone
Production runs in ensemble (cluster) mode; standalone is for learning. Use an odd number of nodes (3 / 5) so a quorum survives 1 / 2 failures.

命令行客户端 zkCli

zkCli.sh is the most direct tool. This connects to localhost:2181 and drops into an interactive prompt:

Shell
bin/zkCli.sh -server 127.0.0.1:2181
Output
Connecting to 127.0.0.1:2181
Welcome to ZooKeeper!
JLine support is enabled
[zk: 127.0.0.1:2181(CONNECTED) 0]

Common commands:

Shell
ls /                      # 列出根下的子节点
create /app "hello"       # 创建持久节点并写入数据
create -e /app/leader ""  # 创建临时节点(会话结束消失)
create -s /queue/task- "" # 创建顺序节点,自动追加序号
get /app                  # 读取数据与 stat 信息
set /app "world"          # 更新数据(dataVersion+1)
delete /app               # 删除节点(有子节点时删不掉)
Output
(zk: 127.0.0.1:2181(CONNECTED) 0) ls /
[zookeeper]

(zk: 127.0.0.1:2181(CONNECTED) 1) create /app "hello"
Created /app

(zk: 127.0.0.1:2181(CONNECTED) 2) get /app
hello
cZxid = 0x2 ...
dataVersion = 0
dataLength = 5
numChildren = 0

Watcher 实战:监听配置变化

Register a getData Watcher on /app, then change the data and the event fires — this is exactly how a config centre works:

Shell
get -w /app               # -w 注册一次性 Watcher
set /app "new-config"     # 另一个会话改数据
Output
(zk: ... CONNECTED 1) get -w /app
hello

WATCHER::
WatchedEvent state:SyncConnected type:NodeDataChanged path:/app

(zk: ... CONNECTED 2) set /app "new-config"
... NodeDataChanged 已触发,下次需重新 get -w

典型应用场景

配置中心

Write config into a znode (e.g. /app/conf); apps getData on boot and register a Watcher. Changing config is a single set; every watching app gets the update within seconds and hot-reloads, no restart.

命名服务 / 注册中心

On startup a service creates an ephemeral sequential node under /services/order (e.g. order-0000000001); it vanishes when the session ends. Callers ls /services/order to get the live instance list — service registration and discovery for free.

分布式锁

To lock: create an ephemeral sequential node under /lock. If yours has the smallest sequence you hold the lock; otherwise watch the previous node's deletion. When it's gone you wake and re-check. Ephemerals guarantee the lock releases if the holder crashes — no deadlock.

选主(Leader Election)

Same idea as the lock: processes create sequential ephemerals under /election; the smallest becomes Leader. When it dies the node disappears, others get the event, and the next-smallest takes over. This smallest-wins pattern powers leader election in HBase, Kafka and more.

集群与选举概览

In a cluster, nodes take three roles: Leader handles writes and broadcasts; Follower votes and serves reads; Observer replicates but does not vote, scaling reads without hurting write latency. The ZAB protocol keeps every node consistent.

A three-node cluster lists every member in zoo.cfg:

PROPERTIES
tickTime=2000
dataDir=/var/lib/zookeeper
clientPort=2181
server.1=10.0.0.1:2888:3888
server.2=10.0.0.2:2888:3888
server.3=10.0.0.3:2888:3888

Port 2888 is for peer-to-peer sync, 3888 is for leader election. Each machine writes its id (1 / 2 / 3) into dataDir/myid. Election needs a majority: the first node to win more than half the votes becomes Leader.

All nodes must share the exact same zoo.cfg; only myid differs. A mismatched or missing server.N is the most common reason a cluster never elects a leader.

小结

  1. ZooKeeper = in-memory node tree + Watcher, purpose-built for coordination
  2. Persistent / ephemeral / sequential nodes; ephemerals underpin leader election and liveness
  3. Watchers fire once; re-register to keep watching; versions give optimistic locking
  4. Config centre, discovery, distributed lock and leader election are the four classic use cases
  5. Run an odd-sized cluster in production; ZAB + quorum election guarantee consistency and availability

Friends & Partners