2024-07-08
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
ZooKeeper is a highly available distributed coordination service that is widely used in distributed systems to solve the consistency problem of distributed systems. The following will introduce the underlying principles of ZooKeeper in detail, including its architecture, data model, core mechanism, and consistency protocol.
ZooKeeper adopts a master-slave architecture, which is usually composed of a Leader and several Followers, as well as Observer nodes as non-voting nodes to share the pressure of read requests.
ZooKeeper stores data in a tree structure similar to a file system, and each node is called a znode.
A session is established between each client and the ZooKeeper cluster to maintain the connection status and manage temporary nodes. ZooKeeper detects the client's connection status through a heartbeat mechanism. If no heartbeat is received within a certain period of time, the session is considered disconnected.
In order to ensure data consistency of each node, ZooKeeper adopts a data synchronization mechanism. When the Leader node processes a write request, it will send the change operation to all Follower nodes. After accepting the change operation, the Follower node confirms it. Ultimately, the Leader node decides whether the change operation is successful.
ZooKeeper supports the Watch mechanism. The client can register a Watch on a specified znode. When the data or child nodes of the znode change, ZooKeeper will notify the client.
ZooKeeper uses a consistency protocol called ZAB (Zookeeper Atomic Broadcast) to ensure data consistency. ZAB consists of two phases: election phase and broadcast phase.
When the ZooKeeper cluster is started, or when the leader node fails, an election is required to determine the new leader. The election phase is mainly divided into the following steps:
After the leader is determined, the broadcast phase begins. The leader is responsible for processing the client's write request and broadcasting the change operation to all follower nodes. The specific steps are as follows:
The following is a simple example of using ZooKeeper, showing how to create a node, read node data, and register a Watch.
exist pom.xml
Introduce ZooKeeper client dependency.
xmlCopy code