Netty network programming practice 4, using Netty to implement heartbeat detection mechanism

1. Use Netty to implement heartbeat detection mechanism

Detect the status of long connections through the heartbeat mechanism. Netty implements the heartbeat mechanism through IdleStateHandler. Every once in a while, it sends a heartbeat to the remote end to detect whether the remote end is active.

Second, the server

1. Main program class

package com.guor.demo.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 主程序类
 */
public class HeartNettyServerTest {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        /**
         * EventLoopGroup:事件循环组,是一个线程池,也是一个死循环,用于不断地接收用户请求;
         * serverGroup:用户监听及建立连接,并把每一个连接抽象为一个channel,最后再将连接交给clientGroup处理;
         * clientGroup:真正的处理连接
         */
        EventLoopGroup serverGroup = new NioEventLoopGroup();
        EventLoopGroup clientGroup = new NioEventLoopGroup();
        try {
    
    
            // 服务端启动时的初始化操作
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 1、将serverGroup和clientGroup注册到服务端的Channel上;
            // 2、注册一个服务端的初始化器MyNettyServerInitializer;
            // 3、该初始化器中的initChannel()方法会在连接被注册到Channel后立刻执行;
            // 5、最后将端口号绑定到8080;
            ChannelFuture channelFuture = serverBootstrap.group(serverGroup, clientGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HeartNettyServerInitializer()).bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
    
    
            System.out.println(e);
        }finally {
    
    
            serverGroup.shutdownGracefully();
            clientGroup.shutdownGracefully();
        }
    }
}

2. Custom initializer

package com.guor.demo.heartbeat;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 自定义初始化器
 */
public class HeartNettyServerInitializer extends ChannelInitializer<SocketChannel> {
    
    

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
    
    
        ChannelPipeline pipeline = socketChannel.pipeline();
        /**
         * IdleStateHandler:心跳机制处理器,主要用来检测远端是否读写超时,
         * 如果超时则将超时事件传入userEventTriggered(ctx,evt)方法的evt参数中
         */
        pipeline.addLast("IdleStateHandler",new IdleStateHandler(3,5,7));
        // 自定义处理器
        pipeline.addLast("HeartNettyServerHandler",new HeartNettyServerHandler());
    }
}

3. Custom Processor

package com.guor.demo.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 自定义处理器
 */
public class HeartNettyServerHandler extends SimpleChannelInboundHandler<Object> {
    
    

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    
    

    }

    /**
     * 如果IdleStateHandler检测到了超时事件,则会触发userEventTriggered(ctx,evt)方法,
     * 将超时事件传入evt参数中
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    
    
        if(evt instanceof IdleStateEvent){
    
    
            IdleStateEvent event = (IdleStateEvent)evt;
            String eventType = null;
            switch (event.state()){
    
    
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress()+",超时事件:"+eventType);
            ctx.channel().close();
        }
    }
}

4. By curl http://localhost:8080accessing the Netty server

Start the server and curl http://localhost:8080access the Netty server. If you do not perform any operations at this time, you can see that the server has detected the "read idle" event after 3 seconds.
insert image description here



Java high concurrency programming practical series of articles

Java high-concurrency programming practice 1, locks learned in those years

Java high-concurrency programming practice 2, atomicity, visibility, orderliness, silly and confused

Java high concurrent programming practice 3, Java memory model and Java object structure

Java high-concurrency programming practice 4, the underlying principles of synchronized and Lock

Java high-concurrency programming practice 5, asynchronous annotation @Async custom thread pool

Java high-concurrency programming practice 6, analyze the lock() lock mechanism through AQS source code

Nezha Boutique Series Articles

Summary of Java learning route, brick movers attack Java architects

Summary of 100,000 words and 208 Java classic interview questions (with answers)

21 Tips for SQL Performance Optimization

Java Basic Tutorial Series

Spring Boot advanced practice
insert image description here

Guess you like

Origin blog.csdn.net/guorui_java/article/details/127160950