Zookeeper 05 Sample code-Primary and standby node switching

Source: Internet
Author: User

The switching of main and standby nodes is the basic requirement of distributed application. Now the main and standby node automatic switching function is realized with Zookeeper. Basic ideas:after more than 1 services are started, try to create a zookeeper in theephemeral type of node, zookeeper itself will guarantee that there is only oneServicewill be created successfully, otherServicethrows an exception. 2 Successful creation of the nodeService, as the primary node, continue running3 OtherServiceset a Watcher Monitoring node state,4 If the primary node disappears, the otherthe service receives a notification and tries to createa node of type ephemeral.
public class Master implements watcher {private static final Logger LOG = Loggerfactory.getlogger (Master.class);    Enum Masterstates {RUNNING, elected, notelected};    Private volatile masterstates state = masterstates.running;    Masterstates getState () {return state;    } private static final int session_timeout = 5000;    private static final String connection_string = "10.58.69.142:2181";    private static final String Znode_name = "/master";    Private random random = new Random (System.currenttimemillis ());    Private ZooKeeper ZK;    Private String ServerID = integer.tohexstring (Random.nextint ());    Private volatile Boolean connected = false;    Private volatile Boolean expired = false;    public void Startzk () throws IOException {ZK = new ZooKeeper (connection_string, session_timeout, this);            } public void Stopzk () {if (ZK! = null) {try {zk.close (); } catch (Interruptedexception e) {LOG.WARN ("interrupted while closing ZooKeeper session.", E); }}}/** * Backorder node */public void Enroll () {zk.create (Znode_name, serverid.ge Tbytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, Createmode.ephemeral, Mastercreatecall    back, NULL); } asynccallback.stringcallback mastercreatecallback = new Asynccallback.stringcallback () {@Override Publ                IC void processresult (int rc, string path, Object ctx, string name) {switch (KeeperException.Code.get (RC)) {                    Case CONNECTIONLOSS://network problem, need to check whether the node was created successfully checkmaster ();                Return                    Case ok:state = masterstates.elected;                Break                    Case nodeexists:state = masterstates.notelected;                    Add watcher Addmasterwatcher ();               Break Default:state = masterstates.notelected; Log.error ("Something went wrong when running for master.", Keeperexception.create (Keeperexcepti On.            Code.get (RC), path));        } log.info ("I ' m" + (state = = masterstates.elected? "": "not") + "the leader" + ServerID);    }    };    public void Checkmaster () {Zk.getdata (Znode_name, False, mastercheckcallback, NULL); } asynccallback.datacallback mastercheckcallback = new Asynccallback.datacallback () {@Override public vo ID processresult (int rc, String path, Object ctx, byte[] data, stat stat) {switch (KeeperException.Code.get (RC                    ) {case Connectionloss:checkmaster ();                Return                    Case Nonode://Node not created, re-registered enroll ();                Return Case Ok:if (Serverid.equals (New String (data)) {state = masterstates.elected;                        } else {state = masterstates.notelected;                    Addmasterwatcher ();                } break; Default:LOG.error ("error when reading data.", Keeperexception.create (KeeperException.Code.get (RC), path            ));    }        }    }; void Addmasterwatcher () {zk.exists (Znode_name, Masterexistswatcher, Masterexistscall    back, NULL);            } Watcher Masterexistswatcher = new Watcher () {@Override public void process (Watchedevent event) {                if (event.gettype () = = Event.EventType.NodeDeleted) {Assert znode_name.equals (Event.getpath ());            Enroll ();    }        }    }; Asynccallback.statcallback masterexistscallback = new Asynccallback.statcallback () {public void Processresult (int RC, String path, Object CTX, stat stat) {switch (KeeperException.Code.get (RC)) {case Connectionloss:                    Addmasterwatcher ();                Break                Case Ok:break;                    Case nonode:state = masterstates.running;                    Enroll ();                    Log.info ("It sounds like the previous master was gone," + "so let's ' s run for Master again.");                Break                    Default:checkmaster ();            Break    }        }    };        public static void Main (string[] args) throws Interruptedexception, IOException {Master m = new Master ();        M.startzk ();        while (!m.isconnected ()) {thread.sleep (100);        } m.enroll ();        while (!m.isexpired ()) {thread.sleep (1000);    } M.STOPZK ();    } Boolean isconnected () {return connected; } Boolean IsexpIred () {return expired;        } @Override public void process (Watchedevent e) {log.info ("Processing event:" + e.tostring ());                    if (e.gettype () = = Event.EventType.None) {switch (E.getstate ()) {case syncconnected:                    connected = true;                Break                    Case disconnected:connected = false;                Break                    Case expired:expired = true;                    connected = false;                Log.error ("Session expiration");            Default:break; }        }    }}




Zookeeper 05 Sample code-Primary and standby node switching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.