Database Reference
In-Depth Information
Leader Election Using ZooKeeper
One of the most common uses for ZooKeeper is to manage a quorum of
servers in much the same way it manages itself. In these quorums, one
of the machines is considered to be the Leader, while other machines
are operating as either replicas or as hot-standby servers, depending on
the application.
This example uses the simplest possible algorithm for implementing
leader election:
• Create an ephemeral sequential node in the target path.
• Check the list of children. The smallest node in the list of children is
the leader.
• Otherwise, watch the list of children and try again when it changes.
In this case, the LeaderElection class implements a latching
approach to leader election. First, the class is initialized with a path and
a ZooKeeper client:
public class LeaderElection implements Watcher,
ChildrenCallback {
String path;
ZooKeeper client;
String node;
public Integer lock = new Integer(0);
public boolean leader = false;
public boolean connected = false ;
public LeaderElection(String connect,String path)
throws IOException {
this .path = path;
client = new ZooKeeper(connect, 3000, this );
}
The class registers itself as the Watcher for events on this client
connection. When the client connects to ZooKeeper, it should request a
position in the leadership queue. If the connection fails, it should
Search WWH ::




Custom Search