EmbeddedChannel 可以查看具体的 handler 执行顺序

    1. package channelhandler;
    2. import io.netty.buffer.ByteBufAllocator;
    3. import io.netty.channel.ChannelHandlerContext;
    4. import io.netty.channel.ChannelInboundHandlerAdapter;
    5. import io.netty.channel.ChannelOutboundHandlerAdapter;
    6. import io.netty.channel.ChannelPromise;
    7. import io.netty.channel.embedded.EmbeddedChannel;
    8. import java.nio.charset.StandardCharsets;
    9. /* Netty测试使用Channel,用于判断实际执行的handler顺序 */
    10. public class TestEmbeddedChannel {
    11. public static void main(String[] args) {
    12. ChannelInboundHandlerAdapter h1 = new ChannelInboundHandlerAdapter(){
    13. @Override
    14. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    15. System.out.println("进入自定义入站handler h1");
    16. super.channelRead(ctx, msg);
    17. }
    18. };
    19. ChannelInboundHandlerAdapter h2 = new ChannelInboundHandlerAdapter(){
    20. @Override
    21. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    22. System.out.println("进入自定义入站handler h2");
    23. super.channelRead(ctx, msg);
    24. }
    25. };
    26. ChannelOutboundHandlerAdapter h3 = new ChannelOutboundHandlerAdapter() {
    27. @Override
    28. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    29. System.out.println("进入自定义出站handler h3");
    30. super.write(ctx, msg, promise);
    31. }
    32. };
    33. ChannelOutboundHandlerAdapter h4 = new ChannelOutboundHandlerAdapter() {
    34. @Override
    35. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    36. System.out.println("进入自定义出站handler h4");
    37. super.write(ctx, msg, promise);
    38. }
    39. };
    40. EmbeddedChannel channel = new EmbeddedChannel(h1,h2,h3,h4);
    41. //模拟入站操作
    42. channel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes(StandardCharsets.UTF_8)));
    43. System.out.println("======");
    44. //模拟出站操作
    45. channel.writeOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes(StandardCharsets.UTF_8)));
    46. }
    47. }

    image.png