This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

A preface

Zookeeper is a popular framework, it can handle distributed locks, but also can achieve better calls between services, and it is through notification mechanism to achieve, so how does he achieve it? Let’s talk about it step by step

Data structure of Zookper

  1. Workers is the parent node, and each of the following child nodes holds the information of each slave node in the system
  2. Tasks is the parent node, and the zNode child below holds information about tasks that will be created and waiting to be executed from the node
  3. Assign is the parent node, and the zNode children below hold information about each task assigned to a slave node

Three different types of ZNodes

  • Persistent node: Persisted to hard disks
  • Temporary nodes: Disappear when timeout and active shutdown occur, as does client active deletion
  • Sequential persistent nodes: /tasks/task-1 / Tasks /task-2 You can view the creation sequence of tasks
  • Temporary ordered node: that is, temporary node + order

Design of monitoring and notification

Based on the above knowledge, we have a basic understanding of ZooKeeper. The following is the design of its notification mechanism

The ZooKeeper client sends zooKeeper a task to be executed. After the task is sent, one design is that the client checks whether the task has been executed each time. It is not smart to check the task many times

So ZooKeeper adopts the notification mechanism, which is to set up a monitoring point on ZooKeeper. When the client visits ZooKeeper for the first time, the watcher of the monitoring point is put on ZooKeeper, and then the client does not care. At this time, the consumer visits ZooKeeper and handles the task. Watch will actively send a message to the client to tell the client that the task has been processed. Watcher then removes the task itself, so that the client does not have to query again.

This is the meaning of Watcher, which is a very clever approach, based on which it knows why watcher is used to substitute ZooKeeper.

5 Architecture of Zookeeper

  • Independent mode: The Zookeeper status cannot be replicated on one server
  • Arbitration mode: composed of a group of servers, that is, distributed, multiple servers vote for a primary node