HeartBeat Heartbeat
The necessity of heartbeat detection
1. Cluster heartbeat detection to avoid network interruption
2. Data synchronization: Master node write log, pull master node log from node every time.
The significance of heartbeat detection:
the client and the server have already established a long connection, the client opens the airplane mode, shuts down, shuts down the WiFi, the service side does not ( perceive ) receives the notification ( handremoved) and close the connection.
Core events:
usereventtriggered events for the Channelinboundhandleradapter class
Heartbeat detection Service-side code:
Server Startup class:
1 Public classHeartbeatserver {2 3 Public Static voidMain (string[] args)throwsinterruptedexception {4 5Eventloopgroup Bossgroup =NewNioeventloopgroup ();6Eventloopgroup Workergroup =NewNioeventloopgroup ();7 8 Try{9Serverbootstrap Serverbootstrap =Newserverbootstrap ();Ten Serverbootstrap.group (bossgroup,workergroup). OneChannel (Nioserversocketchannel.class) A. Handler (NewLogginghandler (loglevel.info)) -. Childhandler (NewMyheartbeatinitializer ()); - theChannelfuture channelfuture = Serverbootstrap.bind (8899). sync (); - Channelfuture.channel (). Closefuture (). sync (); -}finally { - bossgroup.shutdowngracefully (); + workergroup.shutdowngracefully (); - } + A } at -}
Heartbeat Detection Initialization class:
1 Public classMyheartbeatinitializerextendsChannelinitializer<socketchannel> {2 @Override3 protected voidInitchannel (Socketchannel ch)throwsException {4 5Channelpipeline Channelpipeline =ch.pipeline ();6 7Channelpipeline.addlast (NewIdlestatehandler (3,7,10, Timeunit.seconds));8Channelpipeline.addlast (NewMyheartbeathandler ());9 Ten } One}
Heartbeat detection Logic Processing handler:
1 Public classMyheartbeathandlerextendsChannelinboundhandleradapter {2 3 @Override4 Public voidUsereventtriggered (Channelhandlercontext ctx, Object evt)throwsException {5 6 if(evtinstanceofidlestateevent) {7Idlestateevent idlestateevent =(idlestateevent) evt;8 9String EventType =NULL;Ten One Switch(Idlestateevent.state ()) { A CaseReader_idle: -EventType = "Read Idle"; - Break; the CaseWriter_idle: -EventType = "Write Free"; - Break; - CaseAll_idle: +EventType = "Read and write Idle"; - Break; + A } at -System.out.println (Ctx.channel (). Remoteaddress () + "Timeout event:" +eventtype); - - Ctx.channel (). Close (); - } - in } -}
Netty Heartbeat Detection Heartbeat (Fri)