ZK Rob the Lord

Source: Internet
Author: User

Package com.autonavi.tinfo.t1.traffic.pub.openlr.util;

Import java.util.Collections;
Import java.util.List;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;

Import Org.apache.zookeeper.Watcher.Event.KeeperState;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

Import Com.github.zkclient.IZkChildListener;
Import Com.github.zkclient.IZkStateListener;
Import com.github.zkclient.ZkClient;

public class Statusmonitor {

Private lock lock = new Reentrantlock ();//Lock Object
Private Boolean Usingha = true;
Private volatile Boolean isleader = false;

private static final Logger Logger = Loggerfactory.getlogger (Statusmonitor.class);
Timeout period
private int zksessiontimeout=5000;
private int zkconnectiontimeout=5000;
private int session_timeout = 5000;
private int connection_timeout = 5000;

Zookeeper Server List
Private String zkserverlist = "10.17.132.71:2181";

Private String Zkserverdir = "Fast-update";
Private String subnode = "OPENLR";

Child nodes created by the current client
Private String Curpath;
Private Zkclient zkclient;
Scheduledexecutorservice intervalmonitorexecutor = Executors.newsinglethreadscheduledexecutor ();

/**
* Connection Zookeeper
*/
public void init () {
Logger.info ("Statusmonitor.init zksessiontimeout:{},zkconnectiontimeout:{}", Zksessiontimeout, Zkconnectiontimeout);
try {
Connect ();
} catch (Exception e) {
This.isleader = false;
Logger.error (E.getmessage (), E);
try {
Connect ();
} catch (Exception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
Logger.error ("error occurs during sync data from ZK");
System.exit (0);
} finally {
;
}
}

Intervalmonitorexecutor.scheduleatfixedrate (New Runnable () {

@Override
public void Run () {
Lock.lock ();
try {
if (zkclient = = null) {
Isleader = false;
Return
}
if (zkclient! = null && zkclient.getzookeeper () = = null) {
Isleader = false;
Return
}
if (zkclient! = null && (!zkclient.getzookeeper (). GetState (). IsAlive ()
|| !zkclient.getzookeeper (). GetState (). isconnected ())) {
Isleader = false;
Return
}
} finally {
Lock.unlock ();
}
}
}, 0, 2, timeunit.seconds);

}

public void Connect () throws Exception {
if (!usingha) {
Return
}

if (this.zkclient! = null) {
This.zkClient.close ();
}
This.zkclient = new Zkclient (zkserverlist, Zksessiontimeout, zkconnectiontimeout);

if (!zkclient.exists ("/" + Zkserverdir)) {
Zkclient.createpersistent ("/" + Zkserverdir, NULL);
}
if (Curpath = = null) {
Curpath = Zkclient.createephemeralsequential ("/" + Zkserverdir + "/" + subnode, "Monitor". GetBytes ());
}

try {
Startwatchingtopicstatus ();
} catch (Exception e) {
TODO auto-generated Catch block
Logger.error (E.getmessage (), E);
Logger.error ("error occurs during sync data from ZK");
System.exit (0);
}
Thread.Sleep (2000);//* *
Handlemonitornodechange ();
}

public void Startwatchingtopicstatus () {
Zktopicstatuslistener Topiceventlistener = new Zktopicstatuslistener ();
Zkconnectedstatuslistener Connectedstatuslistener = new Zkconnectedstatuslistener ();
try {
Zkclient.subscribechildchanges ("/" + Zkserverdir, Topiceventlistener);
Zkclient.subscribestatechanges (Connectedstatuslistener);
} catch (Exception e) {
Logger.error (E.getmessage (), E);
try {
Thread.Sleep (1000);
} catch (Interruptedexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
Startwatchingtopicstatus ();
}

}

public void Stop () {
if (zkclient = = null) {
Logger.warn ("Shutdown topic event Watcher");
Return
}
Stopwatchingtopicevents ();
Zkclient.close ();
Zkclient = null;
}

private void Beleader () {
Logger.info ("This node gains lock {} and becomes leader", Curpath);
SYSTEM.OUT.PRINTLN ("This node gains lock" + Curpath + "and becomes leader");
This.isleader = true;
}

public void Setusingha (Boolean Isusingha) {
This.usingha = Isusingha;
}

public void Setzkserverdir (String zkserverdir) {
This.zkserverdir = Zkserverdir;
}

public Boolean Isusingha () {
return Usingha;
}

public Boolean Isleader () {
return isleader;
}

public void Setzkserverlist (String zkserverlist) {
This.zkserverlist = zkserverlist;
}

/*public int Getsession_timeout () {
return session_timeout;
}

public void setsession_timeout (int session_timeout) {
Session_timeout = Session_timeout;
}

public int getconnection_timeout () {
return connection_timeout;
}

public void setconnection_timeout (int connection_timeout) {
Connection_timeout = Connection_timeout;
}*/

public int getzksessiontimeout () {
return zksessiontimeout;
}

public void setzksessiontimeout (int zksessiontimeout) {
This.zksessiontimeout = Zksessiontimeout;
}

public int getzkconnectiontimeout () {
return zkconnectiontimeout;
}

public void setzkconnectiontimeout (int zkconnectiontimeout) {
This.zkconnectiontimeout = Zkconnectiontimeout;
}

public void Handlemonitornodechange () throws Exception {
This.lock.lock ();
try {
if (zkclient = = null)
Return
if (!zkclient.exists ("/" + Zkserverdir)) {
Zkclient.createpersistent ("/" + Zkserverdir, NULL);
}

Confirm if Curpath is really the smallest node in the list
List<string> childs = Zkclient.getchildren ("/" + Zkserverdir);
if (childs = = NULL | | childs.size () = = 0) {
Create child nodes
Curpath = Zkclient.createephemeralsequential ("/" + Zkserverdir + "/" + subnode, "Monitor". GetBytes ());
Childs = Zkclient.getchildren ("/" + Zkserverdir);
}
Collections.sort (Childs);

String Thisnode = curpath.substring (("/" + Zkserverdir + "/"). Length ());
int index = Childs.indexof (Thisnode);
if (Index < 0) {
Curpath = Zkclient.createephemeralsequential ("/" + Zkserverdir + "/" + subnode, "Monitor". GetBytes ());
Childs = Zkclient.getchildren ("/" + Zkserverdir);
Collections.sort (Childs);
Thisnode = Curpath.substring (("/" + Zkserverdir + "/"). Length ());
index = Childs.indexof (Thisnode);
}

if (index = = 0) {
is indeed the smallest node
Beleader ();
} else {
This.isleader = false;
}
} finally {
This.lock.unlock ();
}
}

Class Zktopicstatuslistener implements Izkchildlistener {

@Override
public void Handlechildchange (String parentpath, list<string> currentchilds) throws Exception {
Handlemonitornodechange ();
}
}

Class Zkconnectedstatuslistener implements Izkstatelistener {

@Override
public void handlestatechanged (Keeperstate state) throws Exception {
TODO auto-generated Method Stub
if (State.equals (state). syncconnected) | | State.equals (state. Connectedreadonly)) {
System.out.println ("Zookeeper start to be connected");
Handlemonitornodechange ();
}
}

@Override
public void Handlenewsession () throws Exception {
TODO auto-generated Method Stub
}

}

public static void Main (string[] args) throws Exception {
Statusmonitor statusmonitor = new Statusmonitor ();
Statusmonitor.setzkserverlist ("10.61.97.23:2181");
Statusmonitor.setusingha (TRUE);

Statusmonitor.init ();

Thread.Sleep (100000000);
}

}

ZK Rob the Lord

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.