zk achieve Services Awards

Non-fair election algorithm
1) PERSISTENT first create a node / server by ZK
2) multiple machines simultaneously create / server / leader EPHEMERAL child node
3) can only create a child node, the creation will fail. Creating a successful node is selected leader node
4) changes all machines monitor / server / leader, once node is deleted, it is re-election, preemptive create / server / leader node, who create success who is the leader.

public static void main(String[] args) throws Exception {
    zk = new ZooKeeper("127.0.0.1:2181", FairSelectDemo.SESSION_TIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println(event.getType() + "---" + event.getPath() + "---" + event.getState());
        }
    });
    //After zk try to start an election 
    Selection (); 

    TimeUnit.HOURS.sleep ( 1 ); // blocking live 
    zk.close (); 
} 

Private  static  void Selection () throws Exception {
     the try {
         // 1, create / server ( this created by zkCli good), 3 parameter nodes represent the public, anyone can change 
        zk.create ( " / Server / Leader " , " node1 " .getBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
         // 2, did not throw an exception, create a node represents the success of the 
        System. OUT .println ( " electoral success " ); 
    } the catch(KeeperException.NodeExistsException E) { 
        System. OUT .println ( " electoral defeat " ); 
    } a finally {
         // 3, listening nodes delete events, if you delete and re-election 
        zk.getData ( " / Server / Leader " , new new Watcher () { 
            @Override 
            public  void Process (WatchedEvent Event ) { 
                the System. OUT .println ( Event .getType () + " --- " + Event .getPath () + " --- " + event.getState());
                try {
                    if (Objects.equals(event.getType(), Event.EventType.NodeDeleted)) {
                        selection();
                    }
                } catch (Exception e) {
                }
            }
        }, null);
    }
}

Fair election algorithm
1) First create a / server node by zk PERSISTENT
2) multiple machines simultaneously create / server / leader EPHEMERAL_SEQUENTIAL child node
3) / server / leader000000xxx after the number that was chosen as leader of the smallest node node
4) all machines change before a monitor / server / leader, such as (leader00001 monitor leader00002) Once a node is deleted, you get all the leader under / server, if you own your own digital smallest was elected leader

public static void main(String[] args) throws Exception {
    zk = new ZooKeeper("127.0.0.1:2181", UnFairSelectDemo.SESSION_TIMEOUT, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println(event.getType() + "---" + event.getPath() + "---" + event.getState());
        }
    });

    LeaderPath String = " / Server / Leader " ; 

    // 1, create / server (this is created by zkCli), note that this is the EPHEMERAL_SEQUENTIAL
     // 2, and non-equity modes are not the same, only you need to create a node on it 
    = zk.create nodeVal (leaderPath, " node1 " .getBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 

    // System.out.println (nodeVal); 

    // try to start after the elections 
    selection (); 

    TimeUnit.HOURS.sleep ( . 1 ); // blocking live 
    zk.close (); 
} 

Private  static  void Selection () throws Exception {
     //2, traversal / subnode the server, to see their number is not the smallest 
    List <String> = zk.getChildren Children ( " / Server " , null ); 
    the Collections.sort (Children); 

    String formerNode = "" ;   // previous node for monitoring 
    for ( int I = 0 ; I <children.size (); I ++ ) { 
        String node = Children. GET (I);
         IF (nodeVal.equals ( " / Server / " + node )) {
             IF (I == 0 ) {
                 // first
                System. OUT .println ( " I was elected leader of the node " ); 
            } the else { 
                formerNode = Children. GET (i - 1 ); 
            } 
        } 
    } 
    IF (! "" .Equals (formerNode)) {
             // they are not first, if the first formerNode should be no value 
        System. OUT .println ( " my campaign failed " );
         // 3, remove the event listener before a node, if you delete and re-election 
        zk.getData ( " / Server / " + formerNode,new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getType() + "---" + event.getPath() + "---" + event.getState());
                try {
                    if (Objects.equals(event.getType(), Event.EventType.NodeDeleted)) {
                        selection();
                    }
                } catch (Exception e) {
                }
            }
        }, null);
    }
    //System.out.println("children:" + children);
}

 But in fact, the above wording is not very rigorous, such as fair elections algorithm, if the intermediate node hung up, assuming there are nodes such as 01,02,03,04 hang 02, 03 have been listening for 02, then 03 should be changed at this time 01 to listen, otherwise, when 01 hung up, without any node to be chosen as leader. In addition, a variety of abnormal conditions we need to deal with their own.


Original: https: //blog.csdn.net/haizeihdj/article/details/80796227

Guess you like

Origin www.cnblogs.com/wujf/p/11008273.html
Recommended