字节跳动就是我心中的耶路撒冷!
netty介绍:
Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。
netty最核心的组件:EventLoop
Event
Channel
ChannelPipeline
ChannelHandler
ChannelContextHandler
netty的组件
Bootstrap:netty的辅助启动器,netty客户端和服务器的入口,Bootstrap是创建客户端连接的启动器,ServerBootstrap是监听服务端端口的启动器,跟tomcat的Bootstrap类似,程序的入口。
Channel:关联jdk原生socket的组件,常用的是NioServerSocketChannel和NioSocketChannel,NioServerSocketChannel负责监听一个tcp端口,有连接进来通过boss reactor创建一个NioSocketChannel将其绑定到worker reactor,然后worker reactor负责这个NioSocketChannel的读写等io事件。
A nexus to a network socket or a component which is capable of I/O operations such as read, write, connect, and bind.A channel provides a user:* the current state of the channel (e.g. is it open? is it connected?),* the [configuration parameters](https://netty.io/4.1/api/io/netty/channel/ChannelConfig.html "interface in io.netty.channel") of the channel (e.g. receive buffer size),* the I/O operations that the channel supports (e.g. read, write, connect, and bind), and* the [`ChannelPipeline`](https://netty.io/4.1/api/io/netty/channel/ChannelPipeline.html "interface in io.netty.channel") which handles all I/O events and requests associated with the channel.
EventLoop: netty最核心的几大组件之一,就是我们常说的 reactor ,人为划分为 boss reactor 和 worker reactor 。 通过 EventLoopGroup ( Bootstrap 启动时会设置 EventLoopGroup )生成,最常用的是nio的 NioEventLoop ,就如同 EventLoop 的名字, EventLoop 内部有一个无限循环,维护了一个 selector ,处理所有注册到 selector 上的 io 操作,在这里实现了一个线程维护多条连接的工作。
ChannelPipeline:
netty最核心的几大组件之一,ChannelHandler的容器,netty处理io操作的通道,与ChannelHandler组成责任链。write、read、connect等所有的io操作都会通过这个ChannelPipeline,依次通过ChannelPipeline上面的ChannelHandler处理,这就是netty事件模型的核心。ChannelPipeline内部有两个节点,head和tail,分别对应着ChannelHandler链的头和尾。
A list of ChannelHandlers which handles or intercepts inbound events and outbound operations of a Channel.ChannelPipeline implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how the ChannelHandlers in a pipeline interact with each other.
ChannelHandler: netty 最核心的几大组件之一, netty 处理 io 事件真正的处理单元,开发者可以创建自己的 ChannelHandler 来处理自己的逻辑,完全控制事件的处理方式。 ChannelHandler 和 ChannelPipeline 组成责任链,使得一组 ChannelHandler 像一条链一样执行下去。 ChannelHandler 分为 inBound 和 outBound ,分别对应 io 的 read 和 write 的执行链。 ChannelHandler 用 ChannelHandlerContext 包裹着,有 prev 和 next 节点,可以获取前后 ChannelHandler , read 时从 ChannelPipeline 的 head 执行到 tail , write 时从 tail 执行到 head ,所以 head 既是 re ad 事件的起点也是 write 事件的终点,与 io 交互最紧密。
使用ChannelHandlerContext在handler之间传递事件public class MyInboundHandler extends ChannelInboundHandlerAdapter {
@Override public void channelActive(ChannelHandlerContext ctx) {
System.out.println("Connected!"); ctx.fireChannelActive(); } } public class MyOutboundHandler extends ChannelOutboundHandlerAdapter {
@Overri