What is the heartbeat detection mechanism
Heartbeat Refers to a TCP long connection in which the client and server periodically send data packets to each other. This ensures the correct running of services and the reliability of online services and TCP long connections. The heartbeat mechanism is that the client periodically sends data packets to the server. The server responds after receiving the data, thus ensuring the TCP long connection. Of course, there is also a way to do the server heartbeat, if the client does not answer, close the corresponding connection, save resources, but this is rare after all!
2 Working principles of netty heartbeat
In netTY, when the client is idle, it can send data packets to the server. After receiving the heartbeat packets, the server replies. The key is how to determine if the client is in write idle state. The IdleStateHandler processor is provided in Netty. You can monitor the read and write status of channels.
- ReaderIdleTime Read timeout
- WriterIdleTime Write timeout
- AllIdleTime Indicates read/write timeout
- Unit Indicates the unit of time
public IdleStateHandler(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
this(false, readerIdleTime, writerIdleTime, allIdleTime, unit);
}
Copy the code
The netty client implements the heartbeat mechanism
AddLast (“ping”, new IdleStateHandler(30, 20, 90, timeUnit.seconds));
Indicates that read is free for 30 seconds and write is free for 20 seconds. Read and write 90 seconds free
public void connect(int port, String host) throws InterruptedException {
// Create a thread group
NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
// Netty starts helper classes
Bootstrap bootstrap = new Bootstrap();
//
bootstrap.group(nioEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// Handle I/O events
ChannelPipeline pipeline = socketChannel.pipeline();
// Heartbeat detection
pipeline.addLast("ping".new IdleStateHandler(30.20.90, TimeUnit.SECONDS));
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
//
pipeline.addLast(newNettyClientHandler()); }});// Asynchronous operation
ChannelFuture connect = bootstrap.connect(host, port).sync();
// Close the client
connect.channel().closeFuture().sync();
// Exit the thread group
nioEventLoopGroup.shutdownGracefully();
}
Copy the code
Then, the userEventTriggered method is implemented in the processor to determine the current channel state, and then send heartbeat packets according to the different state. On the client side, we only need to send heartbeat packets when writing idle.
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
public NettyClientHandler(a) {
super(a); }/ /...
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
switch (e.state()) {
case READER_IDLE:
System.out.println("Read free");
break;
case WRITER_IDLE:
// Write idle, send heartbeat
System.out.println("Write idle. Send heartbeat packet.");
ctx.writeAndFlush("1");
break;
case ALL_IDLE:
System.out.println("Read-write idle");
break;
default:
break; }}super.userEventTriggered(ctx, evt); }}Copy the code
In the test code, the client sends heartbeat packet 1; The server returns to 0.
The client effect picture is as follows
The following is the server effect diagram
This set of tutorials
- Netty introduction (1)
- NettyTCP Sticky Packet Unpacking (2)
- Netty Disconnection and Reconnection (3)
- Netty Heartbeat Detection Mechanism (4)
- Netty encoding and decoding (5)
- The backlog may have been updated