Netty心跳檢測

IdleStateHandler


在這裏插入圖片描述
Netty中的心跳檢測機制,根據這個處理器能及時的檢測到讀/寫/讀寫空閒狀態,根據狀態進行相應的處理。

Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed
read, write, or both operation for a while.

當沒有執行讀、寫、讀寫時觸發IdleStateEvent。

觸發IdleStateEvent後,會將Event傳遞給pipeline的下一個Handler的userEventTriggered方法,重寫此方法對空閒事件進行處理。

代碼示例
Server:

		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try{

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            /**
                             *  1.long readerIdleTime 超過這個時間沒有讀,就會發送心跳包進行檢測
                             *  2.long writerIdleTime 超過這個時間沒有讀,就會發送心跳包進行檢測
                             *  3.long allIdleTime 讀超過這個時間沒有讀寫,就會發送心跳包進行檢測
                             *
                             *  如果沒有進行讀、寫、讀寫,就會觸發IdleStateEvent事件
                             *  當觸發了IdleStateEvent觸發後,就會傳遞給pipeline的下一個handler的userEventTriggered去處理
                             */
                            pipeline.addLast(new IdleStateHandler(3,5,7,TimeUnit.SECONDS));
                            pipeline.addLast(new HeartBeatServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8090).sync();
            channelFuture.channel().closeFuture().sync();

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

ServerHandler:

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()){
                case READER_IDLE:
                    System.out.println("read空閒");
                    break;
                case WRITER_IDLE:
                    System.out.println("write空閒");
                    break;
                case ALL_IDLE:
                    System.out.println("readwrite空閒");
                    break;
            }
            // 根據讀寫空閒進行相應的的操作
            ctx.close();
        }
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章