There are two main ways of doing this:
(a) Squatting leader node-----non-Fair mode
(b) First-come-first-served, which listens to the former-----fair mode
(a) Squatting leader node-----non-Fair mode
1. Create a leader parent node, such as/chroot, and set it as a persist persistent node;
2. Each client competes Leader by creating a Leader node under/chroot, such as/chroot/leader, which is set to ephemeral temporary node;
3. If a client creates a leader node successfully, the client will run successfully for leader;
4. If a client fails to create a leader, the campaign leader fails, and the exist watch Monitor is registered on the/chroot/leader node and is notified once the node is deleted;
5.Leader client can discard leader by deleting leader node;
6. If the leader is down, because the leader node is set to ephemeral temporary node, the leader node will be deleted by itself, while the other nodes can be notified to participate in the next round of leader campaign because they have registered watch on the leader node. Thus ensuring the client to work in the leader role;
(b) First-come-first-served, which listens to the former-----fair mode
1. Create a leader parent node, such as/chroot, and set it as a persist persistent node;
2. Each client competes Leader by creating a Leader node under/chroot, such as/chroot/leader, which is set to ephemeral_sequential temporary sequential node;
3. The client obtains all child nodes under/chroot/through the GetChildren method, and if its registered node ID is the smallest of all child node IDs, the current client campaign leader succeeds;
4. Otherwise, register watch listener on a previous node, and once the previous node is deleted, it is notified that it will return Step3 (however, you cannot think of yourself as the leader node, as the previous node may just be down)
5. Leader nodes can discard leader by deleting the nodes they have created themselves;
How to use Zookepper to Kafka Leader election?