Commit 2764a3fd authored by Mohamad Bashar Desoki's avatar Mohamad Bashar Desoki

Election process

parent 88582424
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class LeaderElection implements Watcher {
private static final String address = "172.29.3.101:2181";
private static final int SESSION_TIMEOUT = 3000; //dead client
private static final String ELECTION_NAMESPACE = "/election";
private String currentZnodeName;
private ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException {
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
LeaderElection leaderElection = new LeaderElection();
leaderElection.connectToZookeeper();
leaderElection.volunteerForLeadership();
leaderElection.electLeader();
leaderElection.run();
leaderElection.close();
System.out.println("Successfully Closed");
}
public void volunteerForLeadership() throws InterruptedException, KeeperException {
String znodePrefix = ELECTION_NAMESPACE + "/c_";
String znodeFullPath = zooKeeper.create(znodePrefix, new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(znodeFullPath);
this.currentZnodeName = znodeFullPath.replace(ELECTION_NAMESPACE + "/", "");
}
public void electLeader() throws InterruptedException, KeeperException {
List<String> children = zooKeeper.getChildren(ELECTION_NAMESPACE, false);
Collections.sort(children);
String smallestChild = children.get(0); //the first element
if (smallestChild.equals(currentZnodeName)) {
System.out.println("I'm a leader");
} else {
System.out.println("I'm not a leader" + smallestChild + " is a leader.");
}
}
private void close() throws InterruptedException {
this.zooKeeper.close();
}
......@@ -44,6 +72,7 @@ public class LeaderElection implements Watcher {
}
}
break;
// case NodeCreated:
// if (watchedEvent.getState() == )
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment