上一篇【第27篇】Netty OP_ACCEPT事件处理源码解析——新连接是怎么被接入的
下一篇【第29篇】Netty OP_READ事件处理源码解析(下)——数据如何在Pipeline中流转
开篇故事
某电商大促,用户投诉"下单按钮点了没反应"。排查发现:Netty Worker线程的读缓冲区太小(256字节),而请求体有4KB,一次读不完需要多次读取,导致延迟暴增。
TCP是流协议,数据可能分片到达。Netty通过循环read()+动态缓冲区优雅解决。
一、OP_READ处理流程总览
NioEventLoop.run()
→ select() ← 返回OP_READ事件
→ processSelectedKeys()
→ NioSocketChannel.unsafe.read() ← 入口
→ NioByteUnsafe.read()
→ allocHandle = recvBufAllocHandle() ← 获取缓冲区分配句柄
→ do {
byteBuf = allocHandle.allocate(allocator) ← 分配ByteBuf
doReadBytes(byteBuf) ← 读取数据到ByteBuf
pipeline.fireChannelRead(byteBuf) ← 触发Handler链
} while (allocHandle.continueReading()) ← 继续读直到无数据
→ pipeline.fireChannelReadComplete() ← 读完成事件
二、核心源码:NioByteUnsafe.read()
public final void read() {
final ChannelConfig config = config();
final ChannelPipeline pipeline = pipeline();
final ByteBufAllocator allocator = config.getAllocator();
final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle();
do {
ByteBuf byteBuf = allocHandle.allocate(allocator); // 1. 分配ByteBuf
allocHandle.lastBytesRead(doReadBytes(byteBuf)); // 2. 读取数据
if (allocHandle.lastBytesRead() <= 0) {
byteBuf.release(); // 没有数据,释放
break;
}
allocHandle.incMessagesRead(1); // 3. 消息计数+1
pipeline.fireChannelRead(byteBuf); // 4. 触发channelRead
} while (allocHandle.continueReading()); // 5. 是否继续读
allocHandle.readComplete();
pipeline.fireChannelReadComplete(); // 6. 触发读完成事件
}
doReadBytes()核心操作:
protected int doReadBytes(ByteBuf byteBuf) throws Exception {
return byteBuf.writeBytes(javaChannel(), byteBuf.writableBytes());
}
// 底层调用:SocketChannel.read(ByteBuffer)
三、RecvByteBufAllocator——动态缓冲区
AdaptiveRecvByteBufAllocator根据历史读取量动态调整缓冲区大小:
// 默认值
static final int DEFAULT_MINIMUM = 64; // 最小64字节
static final int DEFAULT_INITIAL = 1024; // 初始1024字节
static final int DEFAULT_MAXIMUM = 65536; // 最大64KB
// SIZE_TABLE预定义大小列表
private static final int[] SIZE_TABLE = {
16, 32, 48, 64, 80, 96, 112, 128, ... 65536
};
// 自适应算法:如果连续两次读取量等于缓冲区大小,就增大缓冲区
private void record(int actualReadBytes) {
if (actualReadBytes <= SIZE_TABLE[max(0, index - 1)]) {
if (decreaseNow) index = max(index - 1, minIndex); // 减少
} else if (actualReadBytes >= nextReceiveBufferSize) {
index = min(index + 4, maxIndex); // 增大(+4级)
decreaseNow = false;
}
}
四、数据流图
网卡 → 内核缓冲区
↓
SocketChannel.read(ByteBuffer) ← doReadBytes()
↓
ByteBuf (堆外直接内存) ← 从内存池分配
↓
pipeline.fireChannelRead(byteBuf)
↓
ByteToMessageDecoder.channelRead()
→ cumulation(byteBuf) ← 累积到cumulation缓冲区
→ callDecode() ← 循环解码
→ decode(ctx, cumulation, out) ← 用户实现的decode方法
→ pipeline.fireChannelRead(decodedMsg) ← 解码后的消息
↓
业务Handler.channelRead()
五、实战:自定义读缓冲区
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class ReadBufferServer {
public static void main(String[] args) throws Exception {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.RCVBUF_ALLOCATOR,
new AdaptiveRecvByteBufAllocator(512, 2048, 65536))
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
System.out.println("收到消息: " + msg);
}
});
}
});
b.bind(8080).sync().channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
六、总结
| 组件 | 职责 |
|---|---|
NioByteUnsafe.read() | 读取循环的入口 |
doReadBytes() | 调用JDK NIO读取数据到ByteBuf |
RecvByteBufAllocator | 自适应调整缓冲区大小 |
pipeline.fireChannelRead() | 数据传递给Handler链 |
上一篇【第27篇】Netty OP_ACCEPT事件处理源码解析——新连接是怎么被接入的
下一篇【第29篇】Netty OP_READ事件处理源码解析(下)——数据如何在Pipeline中流转
778


——数据是怎么从网卡读进来的&spm=1001.2101.3001.11974&articleId=162115006&d=1&t=3&u=6657262d71cf47078d67c4d971029108)

被折叠的 条评论
为什么被折叠?



