netty心跳机制IdleStateHandler的使用

1,051 阅读1分钟

netty使用IdleStateHandler来检测连接的心跳检测,上demo

MyServer

public class MyServer {
    public static void main(String[] args) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                   
                    pipeline.addLast(new IdleStateHandler(2,10,10, TimeUnit.SECONDS));
                    //加入一个对空闲检测进一步处理的handler(自定义)
                    pipeline.addLast(new MyServerHandler());
                }
            });

            //启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

MyServerHandler

public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)){
            return;
        }
        //将  evt 向下转型 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);
        System.out.println("服务器做相应处理..");

    }
}

IdleStateHandler具体解释

    1. IdleStateHandler 是netty 提供的处理空闲状态的处理器
    2. long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接
    3. long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接
    4. long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接
    5. 当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理,通过调用(触发)下一个handler 的 userEventTiggered , 在该方法中去处理 IdleStateEvent(读空闲,写空闲,读写空闲)
    6. 如果说你在处理读空闲的时候关闭连接了,以后的读写空闲都不会响应了