一文搞懂Netty中Handler的执行顺序

看了很多讲解Netty中InboundHandlerOutboundHandler执行顺序的文章,很少有一篇能完全讲的全的、对的、没有歧义的,在此根据所学、亲自验证得出的结论给大家

举例:netty服务端是这个添加顺序

ch.pipeline().addLast(new InboundHandler1());  
ch.pipeline().addLast(new InboundHandler2()); 
ch.pipeline().addLast(new OutboundHandler1());  
ch.pipeline().addLast(new OutboundHandler2()); 

链表中的顺序为head->in1->in2->out1->out2->tail

1、如果在InboundHandler2中执行的是ctx.channel().writeAndFlush,执行顺序是:

InboundHandler1 
InboundHandler2 
OutboundHandler2
OutboundHandler1

结果证明:执行完InboundHandler1InboundHandler2之后,由于InboundHandler2中执行的是ctx.channel().writeAndFlush,它会直接从tail开始往前找Outbound执行,链表中的顺序为head->in1->in2->out1->out2->tail,所以会执行out2,再执行out1

2、如果在InboundHandler2中执行的是ctx.writeAndFlush,执行顺序是:

InboundHandler1 
InboundHandler2 

结果证明,由于OutboundHandler1与OutboundHandler2的add在InboundHandler2之后,而InboundHandler2中执行的是ctx.writeAndFlush,它会从当前InboundHandler2的位置,往前找Outbound执行,根据链表中的顺序为head->in1->in2->out1->out2->tail,in2之前已经无Outbound,所以不会再有Outbound会执行

上面两个已经能说明问题,为了方便对nettyhandler执行不是太熟悉的读者理解,再举个例子:

ch.pipeline().addLast(new OutboundHandler1());  
ch.pipeline().addLast(new OutboundHandler2());  
ch.pipeline().addLast(new InboundHandler1());  
ch.pipeline().addLast(new InboundHandler2()); 

链表中的顺序为head->out1->out2->in1->in2->tail

1、如果在InboundHandler2中执行的是ctx.channel().writeAndFlush,执行顺序是:

InboundHandler1 
InboundHandler2 
OutboundHandler2
OutboundHandler1 

结果证明,执行完InboundHandler2后,由于InboundHandler2中执行的是ctx.channel().writeAndFlush,它会从tail往前找Outbound执行,而链表中的顺序为head->out1->out2->in1->in2->tail,所以会继续执行到out2、out1

2、如果在InboundHandler2中执行的是ctx.writeAndFlush,执行顺序是:

InboundHandler1
InboundHandler2
OutboundHandler2 
OutboundHandler1

结果证明,执行完InboundHandler2后,由于InboundHandler2中执行的是ctx.writeAndFlush,它会从InboundHandler2位置往前找Outbound执行,而链表中的顺序为head->out1->out2->in1->in2->tail,所以会继续执行到out2、out1

核心最容易让人误解的点总结:

1、ctx.writeAndFlush只会从当前的handler位置开始,往前找outbound执行

2、ctx.pipeline().writeAndFlush与ctx.channel().writeAndFlush会从tail的位置开始,往前找outbound执行

相信你看到这里,基本能掌握channelHandlerContext调用与pipeline、channel调用的区别,但我敢肯定你只能记住3~5天就又忘记了;所以我再加一句记忆方法:

  • 每次add一个channelHandler都会创建一个channelHandlerContext与之绑定,channelHandlerContext的作用就是管理它所关联的channelHandler和在同一个pipeline中的其他channelHandler之间的交互,他是什么?他与某个channelHandler绑定,权利有限,只能从当前他所绑定的channelHandler开始搞事情;
  • 而pipeline与channel比较屌,可以指挥从头或者尾开始搞

附录代码:

package net.xdclass.echo;

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

public class EchoServer {

    private int port;

    public EchoServer(int port){
        this.port = port;
    }

    /**
     * 启动流程
     */
    public void run() throws InterruptedException {

        //配置服务端线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)

                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new OutboundHandler1());
                            ch.pipeline().addLast(new OutboundHandler2());
                            ch.pipeline().addLast(new InboundHandler1());
                            ch.pipeline().addLast(new InboundHandler2());
                        }
                    });

            System.out.println("Echo 服务器启动ing");
            //绑定端口,同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            //等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            //优雅退出,释放线程池
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
    
    public static void main(String [] args) throws InterruptedException {
        int port = 8080;
        if(args.length > 0){
            port = Integer.parseInt(args[0]);
        }
        new EchoServer(port).run();
        //服务启动后,如果没有客户端,想测试服务端功能,可以用telnet:
        // telnet 127.0.0.1 8080 输入内容即可与服务端交互
    }

}




package net.xdclass.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class InboundHandler1 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
        ByteBuf data = (ByteBuf) msg;
        System.out.println("InboundHandler1 channelRead 服务端收到数据:" + data.toString(CharsetUtil.UTF_8));
        // 执行下一个InboundHandler
        ctx.fireChannelRead(Unpooled.copiedBuffer("InboundHandler1 "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}


package net.xdclass.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class InboundHandler2 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
        ByteBuf data = (ByteBuf) msg;
        System.out.println("InboundHandler2 channelRead 服务端收到数据:" + data.toString(CharsetUtil.UTF_8));
        //调用pipeline().writeAndFlush 或者 channel().writeAndFlush,还需要顺着经过Outbound了,再返回给客户端
        //ctx.pipeline().writeAndFlush(Unpooled.copiedBuffer("InboundHandler2 "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
        //ctx.channel().writeAndFlush(Unpooled.copiedBuffer("InboundHandler2 "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
        //调用ChannelHandlerContext.writeAndFlush,若InboundHandler2不是最后一个addLast,则OutboundHandler1、OutboundHandler1不会只想
        ctx.writeAndFlush(Unpooled.copiedBuffer("InboundHandler2 "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}


package net.xdclass.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.CharsetUtil;

public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        ByteBuf data = (ByteBuf) msg;
        System.out.println("OutboundHandler1 write : "+data.toString(CharsetUtil.UTF_8));
        ctx.write(Unpooled.copiedBuffer("OutboundHandler1 "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
        ctx.flush();
    }
}


package net.xdclass.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.CharsetUtil;

public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        ByteBuf data = (ByteBuf) msg;
        System.out.println("OutboundHandler2 write : "+data.toString(CharsetUtil.UTF_8));
        ctx.write(Unpooled.copiedBuffer("  "+data.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8));
        ctx.flush();
    }
}

  • 34
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值