上一篇【第26篇】Netty I/O处理源码解析(上)—— 服务端启动全剖析
下一篇【第28篇】Netty OP_READ事件处理源码解析(上)——数据是怎么从网卡读进来的
开篇故事
某大厂支付系统,双11当天突然出现大量"连接超时"告警。排查后发现:15000个客户端同时发起连接,但服务端只接受了一小部分。
根本原因:SO_BACKLOG设置太小(默认128),全连接队列满了!
TCP连接建立的三次握手:
客户端 服务端
|---SYN------------------>|
|<--SYN+ACK---------------|
|---ACK------------------>| ← 此时连接进入全连接队列
| |
| 然后等待accept()取出
如果全连接队列满了,新的ACK会被丢弃,客户端会重试SYN。这就是"连接超时"的原因。
Netty如何解决?
- 可配置
SO_BACKLOG(option(ChannelOption.SO_BACKLOG, 1024)) - Boss线程尽快accept(),减少队列堆积
- 将NioSocketChannel注册到Worker线程,并行处理
一、OP_ACCEPT处理的完整流程
NioEventLoop.run()
→ select(timeout) ← 等待I/O事件
→ processSelectedKeys()
→ processSelectedKey(k, channel)
→ NioServerSocketChannel.read() ← 这里处理OP_ACCEPT
→ unsafe.read()
→ doReadMessages(List<Object> buf) ← 核心方法!
→ javaChannel().accept() ← JDK NIO accept
→ new NioSocketChannel(this, ch) ← 封装成Netty Channel
→ pipeline.fireChannelRead(NioSocketChannel) ← 触发ServerBootstrapAcceptor
→ ServerBootstrapAcceptor.channelRead()
→ child.pipeline().addLast(childHandler)
→ childGroup.register(child) ← 注册到Worker EventLoop
二、核心源码剖析
2.1 doReadMessages()——accept并创建NioSocketChannel
protected int doReadMessages(List<Object> buf) throws Exception {
// 1. 调用JDK NIO accept
SocketChannel ch = SocketUtils.accept(javaChannel());
try {
if (ch != null) {
// 2. 封装成Netty NioSocketChannel,添加到List
buf.add(new NioSocketChannel(this, ch));
return 1;
}
} catch (Throwable t) {
// 异常处理
}
return 0;
}
关键点:一次accept多个连接(循环accept直到返回null),批量处理提升效率。
2.2 NioSocketChannel的构造过程
public NioSocketChannel(Channel parent, SocketChannel socket) {
super(parent, socket); // → AbstractNioChannel
config = new NioSocketChannelConfig(this, socket.socket());
}
// AbstractNioChannel
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;
this.readInterestOp = readInterestOp; // SelectionKey.OP_READ
ch.configureBlocking(false); // 设置为非阻塞
}
2.3 ServerBootstrapAcceptor——分发到Worker
public void channelRead(ChannelHandlerContext ctx, Object msg) {
final Channel child = (Channel) msg;
// 1. 向子Channel的Pipeline添加childHandler
child.pipeline().addLast(childHandler);
// 2. 设置子Channel的Options和Attrs
setChannelOptions(child, childOptions);
setAttributes(child, childAttrs);
// 3. 注册到Worker EventLoopGroup
childGroup.register(child).addListener(future -> {
if (!future.isSuccess()) {
forceClose(child, future.cause());
}
});
}
三、完整流程图
Boss EventLoop (NioEventLoop)
============================
select() 返回OP_ACCEPT事件
↓
processSelectedKeys()
↓
NioServerSocketChannel.unsafe.read()
↓
doReadMessages() × N次
┌─────────────────────────┐
│ javaChannel().accept() │ ← JDK NIO
│ → SocketChannel │
│ → new NioSocketChannel │ ← Netty封装
└─────────────────────────┘
↓
pipeline.fireChannelRead(child)
↓
ServerBootstrapAcceptor.channelRead()
┌──────────────────────────┐
│ 1. child.pipeline() │
│ .addLast(childHandler) │
│ 2. setChannelOptions() │
│ 3. childGroup.register() │
└──────────────────────────┘
↓
Worker EventLoop
===============
doRegister() → OP_READ注册
channelActive → 开始读数据
四、实战:监控连接接入
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.concurrent.atomic.AtomicInteger;
public class AcceptMonitorServer {
private static final AtomicInteger totalConnections = new AtomicInteger(0);
private static final AtomicInteger activeConnections = new AtomicInteger(0);
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)
.option(ChannelOption.SO_BACKLOG, 1024) // 关键参数
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
int total = totalConnections.incrementAndGet();
int active = activeConnections.incrementAndGet();
System.out.printf("新连接: total=%d, active=%d, remote=%s%n",
total, active, ctx.channel().remoteAddress());
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
activeConnections.decrementAndGet();
ctx.fireChannelInactive();
}
});
}
});
ChannelFuture f = b.bind(8080).sync();
System.out.println("服务器启动,SO_BACKLOG=1024");
f.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
五、总结
| 步骤 | 核心类 | 说明 |
|---|---|---|
| accept | javaChannel().accept() | JDK NIO接受连接 |
| 封装 | new NioSocketChannel() | 封装成Netty Channel |
| 分发 | ServerBootstrapAcceptor | 添加Handler并注册到Worker |
| 注册 | childGroup.register() | Worker EventLoop接管 |
上一篇【第26篇】Netty I/O处理源码解析(上)—— 服务端启动全剖析
下一篇【第28篇】Netty OP_READ事件处理源码解析(上)——数据是怎么从网卡读进来的
301




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



