20K Java+AI 岗位高频考点 — Netty是Java网络编程的事实标准,Dubbo/Spring WebFlux/gRPC底层都基于Netty。面试常考Reactor模型、零拷贝、ByteBuf、Pipeline机制、粘拆包处理。
JDK NIO的问题:
1. API复杂(Selector/Channel/Buffer)
2. epoll空轮询bug(JDK未完全修复)
3. 断线重连、半包/粘包需自己实现
4. 线程模型需自己设计
5. 异常处理复杂
Netty优势:
1. API简洁优雅
2. 修复epoll空轮询bug
3. 内置编解码器(解决粘拆包)
4. 成熟的Reactor线程模型
5. 内存管理(池化ByteBuf)
6. 零拷贝支持
7. SSL/OpenSSL支持
使用Netty的框架:
- Dubbo(RPC)
- Spring WebFlux(Web服务器)
- gRPC Java
- Elasticsearch
- Spark
- Minecraft服务器
Reactor主从模型:
Boss Group(Acceptor)
┌──────────────────┐
│ Boss EventLoop │ ×1
│ (监听OP_ACCEPT) │
└────────┬─────────┘
│ accept连接
┌────────▼─────────┐
│ Worker Group │
│ ┌──────────────┐│
│ │EventLoop #1 ││ → Pipeline → Handler链
│ │EventLoop #2 ││ → Pipeline → Handler链
│ │EventLoop #N ││ → Pipeline → Handler链
│ └──────────────┘│
└──────────────────┘
EventLoop = Thread + Selector + TaskQueue
- 一个EventLoop处理多个Channel
- 一个Channel只属于一个EventLoop
- EventLoop串行处理(无线程安全问题)
线程数:
- Boss:通常1个(只负责accept)
- Worker:CPU核心数×2(默认)
- 业务线程池:耗时操作另开线程
Bootstrap/ServerBootstrap:启动引导
EventLoopGroup:线程组
EventLoop:事件循环(单线程)
Channel:网络连接(Socket封装)
ChannelPipeline:处理器链
ChannelHandler:处理器(业务逻辑)
ChannelHandlerContext:处理器上下文
ByteBuf:字节缓冲区
ChannelFuture:异步操作结果
AttributeKey:Channel附带属性
组件关系:
Bootstrap
→ EventLoopGroup(Boss + Worker)
→ EventLoop(Selector + Thread)
→ Channel(Socket)
→ ChannelPipeline(双向链表)
→ ChannelHandler链
→ ByteBuf(数据载体)
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS))
.addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 4))
.addLast(new LengthFieldPrepender(4))
.addLast(new StringDecoder(StandardCharsets.UTF_8))
.addLast(new StringEncoder(StandardCharsets.UTF_8))
.addLast(new MyBusinessHandler());
}
});
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
JDK ByteBuffer问题:
1. 固定长度,不能动态扩容
2. flip()切换读写模式(容易忘)
3. 只有一个position指针
ByteBuf优势:
1. 双指针(readerIndex/writerIndex),无需flip
2. 动态扩容(writeBytes自动扩容)
3. 池化(PooledByteBufAllocator)
4. 多种类型(堆内/堆外/组合)
5. 引用计数(Reference Counted)
类型:
HeapByteBuf → JVM堆内存(GC管理)
DirectByteBuf → 堆外内存(无GC,零拷贝友好)
CompositeByteBuf → 多个ByteBuf逻辑合并(零拷贝)
UnpooledByteBuf → 非池化(简单场景)
读写示例:
ByteBuf buf = Unpooled.buffer(256);
buf.writeInt(100); // 写
buf.writeBytes("hello".getBytes());
int value = buf.readInt(); // 读
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
Netty内存分配器:PooledByteBufAllocator(默认)
分配策略(jemalloc思想):
- Arena:大块内存区域
- Tiny:0-512B
- Small:512B-8KB
- Normal:8KB-16MB(Page级别)
- Huge:>16MB(直接mmap)
池化好处:
1. 减少GC压力(复用ByteBuf)
2. 减少内存分配开销
3. 堆外内存避免GC停顿
使用规范:
// 1. 池化分配
ByteBuf buf = ctx.alloc().buffer(1024);
try {
buf.writeBytes(data);
ctx.writeAndFlush(buf);
} finally {
buf.release(); // 引用计数-1,归还池
}
// 2. 注意引用计数
// writeAndFlush会自动release
// 如果不发送,需要手动release
// 3. 调优
-Dio.netty.allocator.numHeapArenas=4
-Dio.netty.allocator.numDirectArenas=4
传统数据传输(4次拷贝):
磁盘 → 内核缓冲区 → 用户缓冲区 → Socket缓冲区 → 网卡
Netty零拷贝:
1. CompositeByteBuf:合并多个ByteBuf,逻辑上合并不物理拷贝
ByteBuf header = ...;
ByteBuf body = ...;
CompositeByteBuf message = Unpooled.wrappedBuffer(header, body);
2. FileRegion:文件传输,直接sendfile
FileRegion region = new DefaultFileRegion(fileChannel, 0, size);
channel.writeAndFlush(region);
3. DirectByteBuf:堆外内存,减少一次拷贝
4. Unpooled.wrappedBuffer:包装已有数组,不拷贝
Netty零拷贝 vs OS零拷贝:
- OS零拷贝:sendfile/splice(内核态完成)
- Netty零拷贝:减少用户态数据拷贝(CompositeByteBuf)
- 两者可叠加使用
Pipeline = ChannelHandler的双向链表
入站(Inbound):数据从网络→应用
HeadContext → Decoder → BusinessHandler → TailContext
出站(Outbound):数据从应用→网络
TailContext → Encoder → HeadContext
Handler类型:
ChannelInboundHandler → 处理入站事件(读数据)
ChannelOutboundHandler → 处理出站事件(写数据)
ChannelDuplexHandler → 双向处理
执行流程(读):
网络数据 → HeadContext.read() → Decoder.channelRead() → BusinessHandler.channelRead()
↓ 解码为Java对象 ↓ 业务处理
执行流程(写):
BusinessHandler → ctx.writeAndFlush(msg) → Encoder.write() → HeadContext.write() → 网络
↓ 编码为字节
TCP是流式协议,没有消息边界:
粘包:两个小包合并为一个 [msg1][msg2] → [msg1+msg2]
拆包:一个大包拆为两个 [msg] → [msg_part1][msg_part2]
解决方案:
1. 固定长度:FixedLengthFrameDecoder(100)
2. 分隔符:DelimiterBasedFrameDecoder
3. 长度字段:LengthFieldPrepender + LengthFieldBasedFrameDecoder(最常用)
4. 自定义协议:协议头+消息体
LengthField方案(最推荐):
消息格式:[长度(4字节)][消息体]
编码(LengthFieldPrepender):
"hello" → [0x00 0x00 0x00 0x05][h][e][l][l][o]
解码(LengthFieldBasedFrameDecoder):
new LengthFieldBasedFrameDecoder(
1024 * 1024, // maxFrameLength
0, // lengthFieldOffset
4, // lengthFieldLength
0, // lengthAdjustment
4 // initialBytesToStrip(跳过长度字段)
)
// 协议格式:[魔数(2B)][版本(1B)][类型(1B)][长度(4B)][消息体]
public class MyProtocolDecoder extends ByteToMessageDecoder {
private static final int HEADER_SIZE = 8;
private static final short MAGIC = 0x55AA;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
if (in.readableBytes() < HEADER_SIZE) return;
in.markReaderIndex();
short magic = in.readShort();
if (magic != MAGIC) {
ctx.close();
return;
}
byte version = in.readByte();
byte type = in.readByte();
int length = in.readInt();
if (in.readableBytes() < length) {
in.resetReaderIndex();
return;
}
byte[] body = new byte[length];
in.readBytes(body);
out.add(new MyMessage(version, type, body));
}
}
// IdleStateHandler:检测空闲连接
pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
// 30秒没读到数据 → 触发userEventTriggered
// 心跳Handler
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
// 30秒没收到数据,关闭连接
ctx.close();
}
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
// 连接建立,启动心跳发送
scheduledFuture = ctx.executor().scheduleAtFixedRate(() -> {
ctx.writeAndFlush(new HeartbeatMessage());
}, 0, 10, TimeUnit.SECONDS);
}
}
// WebSocket服务端
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(65536))
.addLast(new WebSocketServerCompressionHandler())
.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536))
.addLast(new WebSocketFrameHandler());
}
}
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
if (frame instanceof TextWebSocketFrame textFrame) {
String request = textFrame.text();
ctx.writeAndFlush(new TextWebSocketFrame("Echo: " + request));
}
}
}
1. Reactor主从线程模型
Boss接收连接,Worker处理IO
2. NIO多路复用
一个线程处理多个连接
3. 零拷贝
CompositeByteBuf / FileRegion / DirectByteBuf
4. 内存池化
PooledByteBufAllocator(jemalloc算法)
5. 无锁设计
EventLoop串行执行(单线程)
TaskQueue避免锁竞争
6. 高效序列化
支持Protobuf/MessagePack/Kryo
7. epoll优化
NativeEpoll(Linux下使用)
Netty EpollEventLoopGroup
8. 灵活TCP参数
TCP_NODELAY(禁用Nagle算法)
SO_REUSEADDR
SO_BACKLOG
WRITE_BUFFER_WATER_MARK
// RPC客户端代理
public class RpcClient {
private final Map<String, CompletableFuture<Object>> pendingRequests = new ConcurrentHashMap<>();
private Channel channel;
public <T> T getService(Class<T> serviceClass) {
return (T) Proxy.newProxyInstance(
serviceClass.getClassLoader(),
new Class[]{serviceClass},
(proxy, method, args) -> {
String requestId = UUID.randomUUID().toString();
RpcRequest request = new RpcRequest(requestId,
serviceClass.getName(), method.getName(),
method.getParameterTypes(), args);
CompletableFuture<Object> future = new CompletableFuture<>();
pendingRequests.put(requestId, future);
channel.writeAndFlush(request);
return future.get(5, TimeUnit.SECONDS);
});
}
// 响应处理
public class ResponseHandler extends SimpleChannelInboundHandler<RpcResponse> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, RpcResponse resp) {
CompletableFuture<Object> future = pendingRequests.remove(resp.getRequestId());
if (future != null) {
if (resp.getError() != null) {
future.completeExceptionally(new RuntimeException(resp.getError()));
} else {
future.complete(resp.getResult());
}
}
}
}
}
Dubbo默认使用Netty作为通信框架:
Dubbo协议格式:
[Magic(2B)][Flag(1B)][Status(1B)][RequestId(8B)][DataLength(4B)][Body]
Dubbo Netty配置:
<dubbo:protocol name="dubbo" port="20880"
server="netty" client="netty"
iothreads="4" threads="200" />
线程模型:
Netty IO线程 → 反序列化 → Dubbo业务线程池 → 服务端方法
↓
ThreadPoolExecutor
(fixed/cached/limited)
Dubbo 3.x Triple协议:
- 基于HTTP/2
- 兼容gRPC
- 仍用Netty作为底层
1. 主从Reactor:Boss接收,Worker处理
2. NIO多路复用:一个线程管理多个连接
3. 无锁串行化:EventLoop单线程执行
4. 内存池化:避免频繁GC
5. 零拷贝:减少数据拷贝
6. epoll:Linux下最高效的IO多路复用
7. 适当的线程数:Worker = CPU×2
关键指标:
- 单机10万+连接
- 百万级消息/秒吞吐
- P99延迟 < 1ms
问题:JDK NIO的epoll空轮询bug
- Selector.select()应该阻塞,但突然返回0
- 导致CPU 100%
- JDK至今未完全修复(声称修复但仍有报告)
Netty修复:
1. 检测select()空返回次数
2. 超过阈值(默认512次)重建Selector
3. 将所有Channel注册到新Selector
源码位置:
NioEventLoop.select() → unexpectedSelectorWakeup → rebuildSelector
也可以使用Netty自己的Epoll:
// Linux下推荐
EventLoopGroup group = new EpollEventLoopGroup();
ServerBootstrap b = new ServerBootstrap()
.group(group)
.channel(EpollServerSocketChannel.class);
Netty内存泄漏检测:
-Dio.netty.leakDetection.level=PARANOID
级别:
DISABLED → 关闭检测
SIMPLE → 采样1%(默认)
ADVANCED → 采样1%,报告分配栈
PARANOID → 100%检测(开发/测试用)
泄漏报告示例:
LEAK: ByteBuf.release() was not called before it's garbage-collected.
Recent access records:
#1: io.netty.handler.codec.ByteToMessageDecoder.channelRead(...)
...
常见泄漏场景:
1. ByteBuf用完未release()
2. Decoder中引用了ByteBuf但未释放
3. 异常路径忘记release
修复:
// 使用try-finally确保释放
ByteBuf buf = ctx.alloc().buffer();
try {
// 使用buf
} finally {
buf.release();
}
// 或使用SimpleChannelInboundHandler
// 自动释放消息(autoRelease=true,默认)
Netty:
- 网络框架(传输层)
- 自定义协议(TCP/UDP/HTTP)
- RPC框架底层
- 需要自己写Handler
Spring WebFlux:
- Web框架(应用层)
- 基于Reactor(响应式编程)
- 默认使用Netty作为HTTP服务器
- 提供注解式开发
关系:WebFlux → Reactor → Netty
选型:
- 自定义协议/RPC → 直接用Netty
- Web应用/REST API → Spring WebFlux
- 需要Servlet兼容 → Spring MVC
Spring WebFlux Netty配置:
@Bean
public NettyReactiveWebServerFactory serverFactory() {
NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory();
factory.addServerCustomizers(server -> server
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.TCP_NODELAY, true));
return factory;
}
架构:
Client → WebSocket → Netty Gateway → MQ → Push Service → Netty → Client
设计要点:
1. 长连接管理:
- ChannelGroup管理所有连接
- 用户ID→Channel映射
- 心跳保活(30秒)
2. 消息可靠性:
- 消息ACK机制
- 离线消息存储
- 消息去重(幂等ID)
3. 扩展性:
- 分片:按用户ID哈希到不同Netty实例
- Redis Pub/Sub跨实例通知
- 消息队列解耦
4. 性能:
- EpollEventLoop(Linux)
- 池化ByteBuf
- 批量flush(write → flush合并)
- 压缩(WebSocket permessage-deflate)
5. 监控:
- 在线连接数
- 消息推送延迟
- 消息送达率
- Channel异常断开率
Netty三核心:EventLoop(单线程串行)、Pipeline(双向链表)、ByteBuf(双指针+池化)
>
粘拆包四解法:固定长度、分隔符、长度字段(推荐)、自定义协议
>
零拷贝三招:CompositeByteBuf合并、FileRegion传文件、DirectBuffer堆外
>
高性能五要素:Reactor主从、无锁串行、内存池化、零拷贝、epoll优化