使用 Netty 实现心跳检测机制

x33g5p2x  于2022-05-30 转载在 其他  
字(3.0k)|赞(0)|评价(0)|浏览(224)

一 点睛

一般是通过心跳机制来检测长连接的状态。Netty 是通过 IdleStateHandler 来实现心跳机制,每隔一段时间,就向远端发出一次心跳,用于检测远端是否处于活动状态。

二 实战

1 主程序类

package netty.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 MyNettyServerTest {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // ServerBootstrap:服务端启动时的初始化操作
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 将 bossGroup 和 workerGroup 注册到服务端的 Channel 上,并注册一个服务端的初始化器 NettyServerInitializer
            // 该初始化器中的 initChannel() 方法,会在连接被注册后立刻执行
            // 最后将端口号绑定到 8888
            ChannelFuture channelFuture = serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new MyNettyServerInitializer()).bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

2 自定义初始化器

package netty.heartbeat;

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

import java.util.concurrent.TimeUnit;

public class MyNettyServerInitializer extends ChannelInitializer<SocketChannel> {
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
        /*
            IdleStateHandler:心跳机制处理器,主要用来检测远端是否读写超时,如果超时则将超时事件传入到 userEventTriggered(ctx,evt) 方法的 evt 参数中
            IdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds,int allIdleTimeSeconds,TimeUnit unit)的参数含义如下:
            readerIdleTimeSeconds:如果指定时间内没有检测到远端的读操作,则会触发形成 IdleState.READER_IDLE (读空闲)状态;
            writerIdleTimeSeconds:如果指定时间内没有检测到远端的写操作,则会触发形成 IdleState.WRITER_IDLE (写空闲)状态;
            allIdleTimeSeconds:如果指定时间内没有检测到远端的读和写操作,则会触发形成 IdleState.ALL_IDLE (读写空闲)状态;
            unit:时间单位(默认:秒)
        */
        pipeline.addLast("IdleStateHandler", new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
        // 自定义处理器
        pipeline.addLast("MyNettyServerHandler", new MyNettyServerHandler());
    }
}

3 自定义处理器

package netty.heartbeat;

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

public class MyNettyServerHandler extends SimpleChannelInboundHandler<Object> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    }

    // 如果 IdleStateHandler 检测到了超时事件,则会触发 userEventTriggered 方法
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            // 获取超时事件:READER_IDLE、WRITER_IDLE或ALL_IDLE
            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();
        }
    }
}

三 测试

1 启动服务端,用 postman 去连接。

2 此时如果客户端不进行任何操作,3s 后就能看到服务端检测到了“读空闲事件”,运行结果如下。
/0:0:0:0:0:0:0:1:60250超时事件:读空闲

相关文章

微信公众号

最新文章

更多