Netty是一個高性能、高擴展性的異步事件驅動的網絡應用程序框架,主要包括三個方面的內容:Reactor線程模型和Netty自定義Channel、ChannelPipeline職責鏈設計模式和內存管理Bytebuf緩沖區.
Netty實現了Reactor線程模型,Reactor模型中有四個核心概念:Resource資源、同步事件復用器、分配器和請求處理器
下面給出官方的demo
public final class EchoServer { static final int PORT = Integer.parseInt(System.getProperty("port", "8080")); public static void main(String[] args) throws Exception { // Configure the server. // 創建EventLoopGroup accept線程組 NioEventLoop EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 創建EventLoopGroup I/O線程組 EventLoopGroup workerGroup2 = new NioEventLoopGroup(1); try { // 服務端啟動引導工具類 ServerBootstrap b = new ServerBootstrap(); // 配置服務端處理的reactor線程組以及服務端的其他配置 b.group(bossGroup, workerGroup2).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new EchoServerHandler()); } }); // 通過bind啟動服務 ChannelFuture f = b.bind(PORT).sync(); // 阻塞主線程,知道網絡服務被關閉 f.channel().closeFuture().sync(); } finally { // 關閉線程組 bossGroup.shutdownGracefully(); workerGroup2.shutdownGracefully(); } } }
public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("收到數據:" + ((ByteBuf)msg).toString(Charset.defaultCharset())); ctx.write(Unpooled.wrappedBuffer("98877".getBytes())); // ((ByteBuf) msg).release(); ctx.fireChannelRead(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } }
Netty中使用EventLoogGroup來描述事件輪詢,EventLoogGroup的初始化過程如下
EventLoop自身實現了Executor接口,當調用executor方法提交任務時,EventLoop會判斷自身run方法是否被執行,如果未啟動則調用內置的executor創建新的線程來觸發run方法, EventLoop初始化過程如下(圖片中關鍵代碼行數對應Netty源碼版本為maven: io.netty:netty-all:4.1.32-Final)
端口綁定過程
Netty中的Channel是一個抽象概念,可以看作是對NioChannel的增強,主要api如下:
Netty中Handler處理器使用了責任鏈模式,這也是Netty高擴展性的原因之一,Netty中通過ChannelPipeline來保存Channel中處理器信息,ChannelPipeline是線程安全的,ChannelHandler可以在任何時刻刪除和添加,例如在即將交換敏感信息時加入加密處理,交換完畢后再刪除它.
Netty中的入站事件和出站事件
Netty中的處理器
不同的事件會觸發Handler類執行不同的方法