【Netty源码解读和权威指南】第90篇:手写MiniNetty——理解Netty设计精髓的最佳方式 上一篇【第89篇】深入理解Netty内存屏障与JMM——如何保证并发安全系列完结感谢阅读一、MiniNetty架构MiniNetty核心组件 ┌──────────────────────────────┐ │ Bootstrap (启动器) │ ├──────────────────────────────┤ │ EventLoop (事件循环) │ │ └── Selector │ ├──────────────────────────────┤ │ Channel (网络通道) │ │ └── Pipeline (处理链) │ │ ├── HeadContext │ │ ├── Handler1 │ │ ├── Handler2 │ │ └── TailContext │ ├──────────────────────────────┤ │ ByteBuf (缓冲区) │ └──────────────────────────────┘二、核心实现EventLoop——事件循环publicclassMiniEventLoopextendsThread{privatefinalSelectorselector;privatefinalQueueRunnabletaskQueuenewConcurrentLinkedQueue();privatevolatilebooleanrunningtrue;publicMiniEventLoop()throwsIOException{this.selectorSelector.open();}publicvoidregister(ServerSocketChannelssc)throwsException{ssc.configureBlocking(false);ssc.register(selector,SelectionKey.OP_ACCEPT);}Overridepublicvoidrun(){while(running){try{selector.select(1000);// 阻塞1秒for(SelectionKeykey:selector.selectedKeys()){if(key.isAcceptable())handleAccept(key);if(key.isReadable())handleRead(key);}// 执行任务队列Runnabletask;while((tasktaskQueue.poll())!null)task.run();}catch(Exceptione){}}}publicvoidexecute(Runnabletask){taskQueue.offer(task);}}Channel——网络通道publicclassMiniChannel{privatefinalSocketChannelsocketChannel;privatefinalMiniPipelinepipelinenewMiniPipeline();privatefinalMiniEventLoopeventLoop;publicMiniChannel(SocketChannelsc,MiniEventLooploop){this.socketChannelsc;this.eventLooploop;}publicvoidread()throwsException{ByteBufferbufByteBuffer.allocate(1024);intlensocketChannel.read(buf);if(len0){buf.flip();pipeline.fireChannelRead(buf);}}publicvoidwrite(Objectmsg)throwsException{ByteBufferbuf(ByteBuffer)msg;socketChannel.write(buf);}}Pipeline——责任链publicclassMiniPipeline{privatefinalMiniHandlerContextheadnewMiniHandlerContext(null);privatefinalMiniHandlerContexttailnewMiniHandlerContext(null);publicMiniPipeline(){head.nexttail;tail.prevhead;}publicvoidaddLast(MiniHandlerhandler){MiniHandlerContextctxnewMiniHandlerContext(handler);ctx.prevtail.prev;ctx.nexttail;tail.prev.nextctx;tail.prevctx;}publicvoidfireChannelRead(Objectmsg){head.next.handler.channelRead(head.next,msg);}}ByteBuf——缓冲区publicclassMiniByteBuf{privatebyte[]buffer;privateintreaderIndex;privateintwriterIndex;publicMiniByteBuf(intcapacity){this.buffernewbyte[capacity];}publicvoidwriteBytes(byte[]src){ensureCapacity(writerIndexsrc.length);System.arraycopy(src,0,buffer,writerIndex,src.length);writerIndexsrc.length;}publicbyte[]readBytes(intlength){byte[]dstnewbyte[length];System.arraycopy(buffer,readerIndex,dst,0,length);readerIndexlength;returndst;}publicintreadableBytes(){returnwriterIndex-readerIndex;}}三、完整服务端publicclassMiniNettyServer{publicstaticvoidmain(String[]args)throwsException{MiniEventLooploopnewMiniEventLoop();loop.start();ServerSocketChannelsscServerSocketChannel.open();ssc.bind(newInetSocketAddress(8080));loop.register(ssc);System.out.println(MiniNetty Server started on port 8080);}}四、与真实Netty对比组件MiniNetty真实NettyEventLoopSelector QueueNioEventLoopChannel包装SocketChannelNioSocketChannelPipeline简单链表DefaultChannelPipelineByteBuf字节数组PooledByteBuf通过实现这210行代码你理解了Netty四大核心的设计精髓五、系列终章本系列共90篇文章覆盖了NIO基础与Netty入门核心组件源码解析I/O处理与内存管理多协议开发实战高级特性与性能调优分布式综合应用感谢阅读如有疑问欢迎交流讨论。上一篇【第89篇】深入理解Netty内存屏障与JMM——如何保证并发安全系列完结感谢阅读