如何在税局网站上做税种认定,杭州seo培训学校,苏州设计网页网站,网络优化网站建设学习highlight: arduino-light 服务编排层:ChannelPipeline协调ChannelHandlerHandler EventLoop可以说是 Netty 的调度中心#xff0c;负责监听多种事件类型#xff1a;I/O 事件、信号事件、定时事件等#xff0c;然而实际的业务处理逻辑则是由 ChannelPipeline 中所定义的 Cha… highlight: arduino-light 服务编排层:ChannelPipeline协调ChannelHandlerHandler EventLoop可以说是 Netty 的调度中心负责监听多种事件类型I/O 事件、信号事件、定时事件等然而实际的业务处理逻辑则是由 ChannelPipeline 中所定义的 ChannelHandler 完成的ChannelPipeline 和 ChannelHandler应用开发的过程中打交道最多的组件。 Netty 服务编排层的核心组件 ChannelPipeline 和 ChannelHandler 为用户提供了 I/O 事件的全部控制权。 在学习之前先思考几个问题。 ChannelPipeline 与 ChannelHandler 的关系是什么它们之间是如何协同工作的ChannelHandler 的类型有哪些有什么区别Netty 中 I/O 事件是如何传播的 ChannelPipeline 概述 Pipeline 的字面意思是管道、流水线。它在 Netty 中起到的作用和一个工厂的流水线类似。 原始的网络字节流经过 Pipeline 被一步步加工包装最后得到加工后的成品。 经过前面课程核心组件的初步学习我们已经对 ChannelPipeline 有了初步的印象它是 Netty 的核心处理链用以实现网络事件的动态编排和有序传播。 今天我们将从以下几个方面一起探讨 ChannelPipeline 的实现原理 ChannelPipeline 内部结构ChannelHandler 接口设计ChannelPipeline 事件传播机制ChannelPipeline 异常传播机制。 ChannelPipeline 内部结构 ChannelPipeline 可以看作是 ChannelHandler 的容器载体它是由一组 ChannelHandler 实例组成的内部通过双向链表将不同的 ChannelHandler 链接在一起如下图所示。 当有 I/O 读写事件触发时ChannelPipeline 会依次调用 ChannelHandler 列表对 Channel 的数据进行拦截和处理。 每个 ChannelHandler 都对应一个 ChannelHandlerContext。 所以实际上 ChannelPipeline 维护的是它与 ChannelHandlerContext 的关系。 那么你可能会有疑问为什么这里会多一层 ChannelHandlerContext 的封装呢 其实这是一种比较常用的编程思想。ChannelHandlerContext用于保存ChannelHandler。 ChannelHandlerContext包含了ChannelHandler生命周期的所有事件如 connect、bind、read、 flush、write、close 等。 可以试想一下如果没有ChannelHandlerContext 的这层封装那么我们在做 ChannelHandler 之间传递的时 候。前置后置的通用逻辑就要在每个 ChannelHandler 里都实现一份。 这样虽然能解决问题但是代码结构的耦合会非常不优雅。 根据网络数据的流向ChannelPipeline 分为入站 ChannelInboundHandler和出站 ChannelOutboundHandler。 服务端接收到客户端数据需要先经过 Decoder 入站处理后再通过 Encoder 出站通知客户端。 ChannelPipeline是双向链表的构造。 ChannelPipeline 的双向链表分别维护了HeadContext 和 TailContext 的头尾节点。 我们自定义的ChannelHandler会插入到 Head 和 Tail 之间这两个节点在 Netty 中已经默认实现了它们在 ChannelPipeline 中起到了至关重要的作用。 首先我们看下 HeadContext 和 TailContext 的继承关系如下图所示。 HeadContext:in\out 对于1个请求先由HeadContext处理入栈,经过一系列的入栈处理器然后传递到TailContext,由TailContext往下传递经过一系列的出栈处理器,最后再经过HeadContext返回。 md ---6 ---5 ---4 HeadContext InBoundHandlerOne TailContext OutBoundHandlerOne 1--- 2--- 3--- 顺序是:12346 其中5是入栈已经在2处理过 所以不需要处理。 Inbound第一站 Outbound最后一站 HeadContext 既是 Inbound 处理器也是 Outbound 处理器。 它分别实现了 ChannelInboundHandler 和 ChannelOutboundHandler。 网络数据写入操作的入口就是由 HeadContext 节点完成的。HeadContext 作为 Pipeline 的头结点负责读取数据并开始传递 InBound 事件当数据处理完成后数据会反方向经过 Outbound 处理器最终传递到 HeadContext所以 HeadContext 既是数据读取Inbound事件的第一站又是处理 Outbound 事件的最后一站。 此外 HeadContext 在传递事件之前还会执行一些前置操作。 TailContext Outbound第一站 TailContext 只实现了 ChannelInboundHandler 接口。它会在 ChannelInboundHandler 调用链路的最后一步执行主要用于终止 Inbound 事件传播例如释放 Message 数据资源等。 TailContext 节点作为 OutBound 事件传播的第一站仅仅是将 OutBound 事件传递给下一个节点。 从整个 ChannelPipeline 调用链路来看如果由 Channel 直接触发事件传播那么调用链路将贯穿整个 ChannelPipeline。 然而也可以在其中某一个 ChannelHandlerContext 触发同样的方法这样只会从当前的 ChannelHandler 开始执行事件传播该过程不会从头贯穿到尾在一定场景下可以提高程序性能。 ChannelHandler 接口设计 在学习 ChannelPipeline 事件传播机制之前我们需要了解 I/O 事件的生命周期。 整个 ChannelHandler 是围绕 I/O 事件的生命周期所设计的例如建立连接、读数据、写数据、连接销毁等。 ChannelHandler 有两个重要的子接口ChannelInboundHandler和ChannelOutboundHandler分别拦截入 站和出站的各种 I/O 事件。 1. ChannelInboundHandler 的事件回调方法与触发时机。 | 事件回调方法 | 触发时机 | | ------------------------- | --------------------------------- | | channelRegistered | Channel 被注册到 EventLoop | | channelUnregistered | Channel 从 EventLoop 中取消注册 | | channelActive | Channel 处于就绪状态可以被读写 | | channelInactive | Channel 处于非就绪状态Channel 可以从远端读取到数据 | | channelRead | Channel 可以从远端读取到数据 | | channelReadComplete | Channel 读取数据完成 | | userEventTriggered | 用户事件触发时 | | channelWritabilityChanged | Channel 的写状态发生变化 | | handlerAdded | 当该处理器被添加到pipeline时 | 2. ChannelOutboundHandler 的事件回调方法与触发时机。 ChannelOutboundHandler 的事件回调方法非常清晰直接通过 ChannelOutboundHandler 的接口列表可以看到每种操作所对应的回调方法如下图所示。 这里每个回调方法都是在相应操作执行之前触发在此就不多做赘述了。 此外 ChannelOutboundHandler 中绝大部分接口都包含ChannelPromise 参数以便于在操作完成时能够及时获得通知。 事件 事件枚举 public static final int OP_READ 1 0;//1
public static final int OP_WRITE 1 2;//4
public static final int OP_CONNECT 1 3;//8
public static final int OP_ACCEPT 1 4;//16 事件传播机制 在上文中我们介绍了 ChannelPipeline 可分为入站 ChannelInboundHandler 和出站 ChannelOutboundHandler 两种处理器与此对应传输的事件类型可以分为Inbound 事件和Outbound 事件。 我们通过一个代码示例一起体验下 ChannelPipeline 的事件传播机制。 java package io.netty.example.pipeline; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;/*** Echoes back any received data from a client.*/
public final class EchoServer {public static void main(String[] args) throws Exception {EventLoopGroup workerGroup new NioEventLoopGroup();EventLoopGroup bossGroup new NioEventLoopGroup();try {ServerBootstrap b new ServerBootstrap();b.group(bossGroup, workerGroup)//通过反射创建反射工厂类根据无参构造函数 反射生成实例//将NioServerSocketChannel绑定到了bossGroup//NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup.channel(NioServerSocketChannel.class)//指的是SocketChannel.childOption(ChannelOption.SO_KEEPALIVE, true)//指的是SocketChannel.childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)//默認不使用堆外内存.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//false 不使用堆外内存.childOption(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false))// .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializerSocketChannel() {Overridepublic void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p ch.pipeline();//正常情况p.addLast(SampleInBoundHandlerA, new SampleInBoundHandler(SampleInBoundHandlerA, false));p.addLast(SampleInBoundHandlerB, new SampleInBoundHandler(SampleInBoundHandlerB, false));p.addLast(SampleInBoundHandlerC, new SampleInBoundHandler(SampleInBoundHandlerC, true));p.addLast(SampleOutBoundHandlerA, new SampleOutBoundHandler(SampleOutBoundHandlerA));p.addLast(SampleOutBoundHandlerB, new SampleOutBoundHandler(SampleOutBoundHandlerB));p.addLast(SampleOutBoundHandlerC, new SampleOutBoundHandler(SampleOutBoundHandlerC));}});ChannelFuture f b.bind(8090).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}
} package io.netty.example.pipeline;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;public final class EchoClient {public static void main(String[] args) throws Exception {// Configure the client.EventLoopGroup group new NioEventLoopGroup();try {Bootstrap b new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializerSocketChannel() {Overridepublic void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p ch.pipeline();p.addLast(new EchoClientHandler());}});// Start the client.ChannelFuture f b.connect(127.0.0.1, 8090).sync();// Wait until the connection is closed.f.channel().closeFuture().sync();} finally {// Shut down the event loop to terminate all threads.group.shutdownGracefully();}}
} package io.netty.example.pipeline;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.concurrent.TimeUnit;/*** Handler implementation for the echo client. It initiates the ping-pong* traffic between the echo client and server by sending the first message to* the server.*/
public class EchoClientHandler extends ChannelInboundHandlerAdapter {private final ByteBuf firstMessage;/*** Creates a client-side handler.*/public EchoClientHandler() {firstMessage Unpooled.wrappedBuffer(I am echo message.getBytes());}Overridepublic void channelActive(ChannelHandlerContext ctx) {System.out.println(客户端发送消息 firstMessage.toString());ctx.writeAndFlush(firstMessage);}Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {// ctx.write(msg);}Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException {TimeUnit.SECONDS.sleep(3);ctx.flush();}Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {// cause.printStackTrace();ctx.close();}
} package io.netty.example.pipeline;import io.netty.channel.*;public class SampleInBoundHandler extends ChannelInboundHandlerAdapter {private final String name;private final boolean flush;public SampleInBoundHandler(String name, boolean flush) {this.name name;this.flush flush;}Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//打印消息System.out.println(InBoundHandler: name);//只有是true的时候才会写消息//否则只会读消息if (flush) {ctx.channel().writeAndFlush(msg);} else {super.channelRead(ctx, msg);}}
} package io.netty.example.pipeline;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;public class SampleOutBoundHandler extends ChannelOutboundHandlerAdapter {private final String name;public SampleOutBoundHandler(String name) {this.name name;}Overridepublic void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {System.out.println(OutBoundHandler: name);super.write(ctx, msg, promise);}
} 通过 Pipeline 的 addLast 方法分别添加了三个 InboundHandler 和 OutboundHandler添加顺序都是 A - B - C下图可以表示初始化后 ChannelPipeline 的内部结构。 *当客户端向服务端发送请求时会触发 SampleInBoundHandler 调用链的 channelRead 事件。经过 SampleInBoundHandler 调用链处理完成后在 SampleInBoundHandlerC 中会调用 writeAndFlush 方法向客户端写回数据此时会触发 SampleOutBoundHandler 调用链的 write 事件。** 最后我们看下代码示例的控制台输出 方向:IN先进先出OUT:先进后出 由此可见Inbound 事件和 Outbound 事件的传播方向是不一样的。Inbound 事件的传播方向为 Head - Tail而 Outbound 事件传播方向是 Tail - Head两者恰恰相反。 在 Netty 应用编程中一定要理清楚事件传播的顺序。推荐你在系统设计时模拟客户端和服务端的场景画出 ChannelPipeline 的内部结构图以避免搞混调用关系。 异常传播机制 ChannelPipeline 事件传播的实现采用了经典的责任链模式调用链路环环相扣。那么如果有一个节点处理逻辑异常会出现什么现象呢我们通过修改 SampleInBoundHandler 的实现来模拟业务逻辑异常 java package io.netty.example.pipeline; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;/*** Echoes back any received data from a client.*/
public final class EchoServer {public static void main(String[] args) throws Exception {EventLoopGroup workerGroup new NioEventLoopGroup();EventLoopGroup bossGroup new NioEventLoopGroup();try {ServerBootstrap b new ServerBootstrap();b.group(bossGroup, workerGroup)//通过反射创建反射工厂类根据无参构造函数 反射生成实例//将NioServerSocketChannel绑定到了bossGroup//NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup.channel(NioServerSocketChannel.class)//指的是SocketChannel.childOption(ChannelOption.SO_KEEPALIVE, true)//指的是SocketChannel.childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)//默認不使用堆外内存.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//false 不使用堆外内存.childOption(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false))// .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializerSocketChannel() {Overridepublic void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p ch.pipeline();//正常情况/*p.addLast(SampleInBoundHandlerA, new SampleInBoundHandler(SampleInBoundHandlerA, false));p.addLast(SampleInBoundHandlerB, new SampleInBoundHandler(SampleInBoundHandlerB, false));p.addLast(SampleInBoundHandlerC, new SampleInBoundHandler(SampleInBoundHandlerC, true));*/p.addLast(SampleInBoundHandlerA, new SampleExceptionInBoundHandler(SampleInBoundHandlerA, false));p.addLast(SampleInBoundHandlerB, new SampleExceptionInBoundHandler(SampleInBoundHandlerB, false));p.addLast(SampleInBoundHandlerC, new SampleExceptionInBoundHandler(SampleInBoundHandlerC, true));p.addLast(SampleOutBoundHandlerA, new SampleOutBoundHandler(SampleOutBoundHandlerA));p.addLast(SampleOutBoundHandlerB, new SampleOutBoundHandler(SampleOutBoundHandlerB));p.addLast(SampleOutBoundHandlerC, new SampleOutBoundHandler(SampleOutBoundHandlerC));}});ChannelFuture f b.bind(8090).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}
} package io.netty.example.pipeline;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;public class SampleExceptionInBoundHandler extends ChannelInboundHandlerAdapter {private final String name;private final boolean flush;public SampleExceptionInBoundHandler(String name, boolean flush) {this.name name;this.flush flush;}Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {System.out.println(InBoundHandler: name);if (flush) {ctx.channel().writeAndFlush(msg);} else {throw new RuntimeException(InBoundHandler: name);}}Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {System.out.println(InBoundHandlerException: name);ctx.fireExceptionCaught(cause);}
} 在SampleExceptionInBoundHandler的 channelRead 事件处理中第一个 A 节点就会抛出 RuntimeException。同时我们重写了 ChannelInboundHandlerAdapter 中的 exceptionCaught 方法只是在开头加上了控制台输出方便观察异常传播的行为。下面看一下代码运行的控制台输出结果 由输出结果可以看出 ctx.fireExceptionCaugh 会将异常按顺序从 Head 节点传播到 Tail 节点。 如果用户没有对异常进行拦截处理最后将由 Tail 节点统一处理在 TailContext 源码中可以找到具体实现 protected void onUnhandledInboundException(Throwable cause) {try {logger.warn(An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.,cause);} finally {ReferenceCountUtil.release(cause);}
} 虽然 Netty 中 TailContext 提供了兜底的异常处理逻辑但是在很多场景下并不能满足我们的需求。假如你需要拦截指定的异常类型并做出相应的异常处理应该如何实现呢我们接着往下看。 异常处理的最佳实践 在 Netty 应用开发的过程中良好的异常处理机制会让排查问题的过程事半功倍。所以推荐用户对异常进行统一拦截然后根据实际业务场景实现更加完善的异常处理机制。 通过异常传播机制的学习我们应该可以想到最好的方法是在 ChannelPipeline 自定义处理器的末端添加统一的异常处理器此时 ChannelPipeline 的内部结构如下图所示。 用户自定义的异常处理器代码示例如下 java package io.netty.example.pipeline; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;/*** Echoes back any received data from a client.*/
public final class EchoServer {public static void main(String[] args) throws Exception {EventLoopGroup workerGroup new NioEventLoopGroup();EventLoopGroup bossGroup new NioEventLoopGroup();try {ServerBootstrap b new ServerBootstrap();b.group(bossGroup, workerGroup)//通过反射创建反射工厂类根据无参构造函数 反射生成实例//将NioServerSocketChannel绑定到了bossGroup//NioServerSocketChannel接收到请求会创建SocketChannel放入workerGroup.channel(NioServerSocketChannel.class)//指的是SocketChannel.childOption(ChannelOption.SO_KEEPALIVE, true)//指的是SocketChannel.childOption(NioChannelOption.SO_KEEPALIVE, Boolean.TRUE)//默認不使用堆外内存.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//false 不使用堆外内存.childOption(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false))// .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializerSocketChannel() {Overridepublic void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p ch.pipeline();//正常情况/*p.addLast(SampleInBoundHandlerA, new SampleInBoundHandler(SampleInBoundHandlerA, false));p.addLast(SampleInBoundHandlerB, new SampleInBoundHandler(SampleInBoundHandlerB, false));p.addLast(SampleInBoundHandlerC, new SampleInBoundHandler(SampleInBoundHandlerC, true));*/p.addLast(SampleInBoundHandlerA, new SampleExceptionInBoundHandler(SampleInBoundHandlerA, false));p.addLast(SampleInBoundHandlerB, new SampleExceptionInBoundHandler(SampleInBoundHandlerB, false));p.addLast(SampleInBoundHandlerC, new SampleExceptionInBoundHandler(SampleInBoundHandlerC, true));//添加异常处理器p.addLast(new ExceptionHandler());p.addLast(SampleOutBoundHandlerA, new SampleOutBoundHandler(SampleOutBoundHandlerA));p.addLast(SampleOutBoundHandlerB, new SampleOutBoundHandler(SampleOutBoundHandlerB));p.addLast(SampleOutBoundHandlerC, new SampleOutBoundHandler(SampleOutBoundHandlerC));}});ChannelFuture f b.bind(8090).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}
} //进站出站异常处理器
public class ExceptionHandler extends ChannelDuplexHandler {Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {if (cause instanceof RuntimeException) {System.out.println(Handle Business Exception Success.);}}
} 加入统一的异常处理器后可以看到异常已经被优雅地拦截并处理掉了。这也是 Netty 推荐的最佳异常处理实践。 总结 本节课我们深入分析了 Pipeline 的设计原理与事件传播机制。 那么前面的几个问题你是否已经都找到答案,来做个简单的总结 ChannelPipeline 是双向链表结构包含 ChannelInboundHandler 和 ChannelOutboundHandler 两种处理器。ChannelHandlerContext 是对 ChannelHandler 的封装每个 ChannelHandler 都对应一个 ChannelHandlerContext实际上 ChannelPipeline 维护的是与 ChannelHandlerContext 的关系。Inbound 事件和 Outbound 事件的传播方向相反Inbound 事件的传播方向为 Head - Tail而 Outbound 事件传播方向是 Tail - Head。异常事件的处理顺序与 ChannelHandler 的添加顺序相同会依次向后传播与 Inbound 事件和 Outbound 事件无关。