watcher and listener leader election mechanism in Zookeeper

watcher monitor

What is the watcher Interface

Event types represent the same meaning in different notification states differ, the figure below lists common status and event notification type.

 Watcher notify state and the type of event list

The figure lists the most common of several ZooKeeper notify state and event type.
Callback method process ()
process is a callback method Watcher interface, when sending a Watcher ZooKeeper event notifications to the client, the client will perform the corresponding process callback method, enabling handling of the incident. defined process method is as follows:
abstract public void process (WatchedEvent Event);
define the callback method is very simple, we look focus parameter defines the method: WatchedEvent.
WatchedEvent contains three basic properties of each event: notification state (keeperState), event type (the EventType) and a node of the path (path), which is the data structure shown in Figure 7-5. ZooKeeper using WatchedEvent objects to encapsulate and passed to the event server Watcher, thereby facilitating callback method of the server process to handle the event.
Mentioned WatchedEvent, I have to speak under WatcherEvent entity. Generally speaking, the two represents the same thing, is a service package to end the event. The difference is, WatchedEvent is a logical event, for the server and client programs perform logical objects needed in the process, because the WatcherEvent implements serialization interface can be used for network transmission.
After generating WatchedEvent server events, calls getWrapper method to package itself as a sequence of events WatcherEvent, for transmission to the client over the network. After the client receives this event object to the server, will first be reduced to a WatchedEvent WatcherEvent event, and passed to the process method of treatment, it is possible to process callback method parse the complete end of the event according to the service parameters.
One thing to note is that both WatchedEvent or WatcherEvent, which are packaged machine ZooKeeper server-side event and simple. Take, for example, when the data / zk-book this node is changed, the server will send the client a "ZNode data content change" event, the client can only receive the information.

Code

public  class ZkWatcher the implements Watcher {
     // connection address 
    Private  static Final ZK_ADDRESS String = " 0.0.0.0:2181 " ;
     // timeout 
    Private  static Final ZK_SESSION_TIMEOUT Integer = 2000 ;


    private ZooKeeper zooKeeper;

    public ZkWatcher() {
        openConnection(ZK_ADDRESS,ZK_SESSION_TIMEOUT);
    }

    /**
     * Callback method, connection monitor, listening node CRUD
     * @param event
     */
    @Override
    public  void Process (WatchedEvent Event ) {
         // get the current status 
        Event.KeeperState keeperState = Event .getState ();
         // Get the type of notification 
        Event.EventType the eventType = Event .getType ();
         // get operation node path 
        String path = Event .getPath ();

        . The System OUT .println ( " Current status: " + keeperState + " \ t notification type is: " + the eventType + " \ t operation node path: " + path);
         // you have successfully 
        IF (= Event.KeeperState.SyncConnected = keeperState) {
             // connection state 
            IF (== Event.EventType.None the eventType) {
                System. OUT .println ( " ======================== connection event callback ================ ======== " );
            }
            // Create a node 
            IF (Event.EventType.NodeCreated == eventType) {
                System. OUT .println ( " ======================== create node event callbacks =============== ========= " );
            }
            // change the node 
            IF (== Event.EventType.NodeDataChanged the eventType) {
                System. OUT .println ( " ======================== modify node event callback =============== ========= " );
            }
            // delete nodes 
            IF (Event.EventType.NodeDeleted == eventType) {
                System. OUT .println ( " ======================== delete nodes event callbacks =============== ========= " );
            }
        }
    }
    /**
     * Zk connection method
     */
    public void openConnection(String zk_address,Integer zk_sessionout){
        try {
            zooKeeper = new ZooKeeper(zk_address, zk_sessionout, this);
            . System OUT .println ( " !!!!! connection zk success !!!!!!! " );
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }


    /**
     * Close zk connection
     *
     */
     public void closeConnection(){
         try {
             if(zooKeeper!=null){
                 zooKeeper.close();
             }

         } catch (InterruptedException e) {
             e.printStackTrace ();
         }
     }

    /**
     * Add Nodes
     * @param
     */
    public void createNode(String path,String data){
        try {
            //启动监听
            zooKeeper.exists(path,true);
            String result = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            . System OUT .println ( " Creating a Node success: " + the Result);
        } catch (KeeperException e) {
            e.printStackTrace ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }

    /**
     * Modify Node
     */
    public void setNode(String path,String data){

        the try {
             // start listening 
            zooKeeper.exists (path, to true );
            zooKeeper.setData(path, data.getBytes(), -1);
            . System OUT .println ( " modify node successfully " );
        } catch (KeeperException e) {
            e.printStackTrace ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }

    /**
     * Delete node
     */
    public void deleteNode(String path){

        the try {
             // start listening 
            zooKeeper.exists (path, to true );
            zooKeeper.delete(path, -1);
            . System OUT .println ( " delete node successfully " );
        } catch (KeeperException e) {
            e.printStackTrace ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
    public static void main(String[] args) {
        ZkWatcher zkWatcher=new ZkWatcher();
        //zkWatcher.createNode("/zkNode","zkValue");

        zkWatcher.setNode("/zkNode","zkValueSet");

        zkWatcher.deleteNode("/zkNode");

        zkWatcher.closeConnection();
    }
}

 leader election mechanism

Zookeeper Server three roles: Leader, Follower, Observer.
Leader Zookeeper is the core mechanism of the cluster, the main work:
1. Scheduler: scheduling by each service node within the cluster of
2. transaction requests: the unique scheduling and handlers transaction request, assure an orderly transaction processing cluster
Follower main responsibilities:
1. non-transaction requests: Follower deal directly with non-transactional requests for transaction requests, forwarded to the Leader
2.Proposal vote: when the transaction is executed on the Leader, Follower need to vote, Leader really perform
3.Leader elections
Observer main responsibilities:
1. non-transaction requests: Follower deal directly with non-transactional requests for transaction requests, forwarded to the Leader
difference Observer with the Follower:
1.Follower vote: Leader election, proposal proposed vote (transaction execution confirmation)
2.Observer not participate in the vote: only to provide non-transactional processing requests

Concept selection mechanisms
serverId (both server ID myid)
For example, there are three servers, numbered 1,2,3.
The larger number in the choice algorithm greater weight.
zxid (the latest transaction ID both LastLoggedZxid)
maximum ID data stored in the server.
ID greater the value of the new data, the data in the new election algorithms greater the weight.
epoch (logic clock both PeerEpoch)
each server to their vote, or vote to call the number, the same logic clock value of a voting process is the same.
Casting their votes every time this data will increase, and then compared with the value of other voting information server receives the returned.
If you receive less than the results of the current round of voting, the vote invalid and should be updated to the current round and the current voting results.

State election
LOOKING, campaign status.
FOLLOWING, entourage status, synchronization leader status, to vote.
OBSERVING, observe the state of synchronization leader status, does not participate in the vote.
LEADING, the leader state.

Election algorithm
by electionAlg attribute specifies the (1-3) zoo.cfg profile, to understand the algorithm, need some theoretical basis paxos algorithm.
Corresponding to 1: LeaderElection algorithm.
2 corresponds to: AuthFastLeaderElection algorithm.
3 corresponds to: FastLeaderElection default algorithm.

Voting content
voter ID
voter ID data
voters to elect the number of rounds
voters to elect state
elected person ID
elect a several rounds of elections

 

 

 

Guess you like

Origin www.cnblogs.com/dabrk/p/11936057.html