如何编写最小可复现的 Netty 示例?
解读
面试官问“最小可复现”,核心想看三点:
- 你是否真的“跑通”过 Netty,而不是只背八股;
- 能否在 5 分钟内把“服务端+客户端”一次性写对,且线程模型、资源释放、协议编解码都符合生产规范;
- 代码量足够少,但关键细节(EventLoopGroup、ChannelInitializer、ChannelHandler 生命周期、资源关闭)一个不落。
国内面试节奏快,很多候选人直接把 main 方法写在 Handler 里、忘记 shutdownGracefully、混用 BIO 写法,直接被 Pass。因此“最小”不是“最简陋”,而是“最精炼且能直接复制运行”。
知识点
- 线程模型:Boss/EventLoop 分工,避免阻塞 IO 线程;
- Channel 类型:NioServerSocketChannel / NioSocketChannel;
- 责任链:ChannelInitializer 一次性添加 Handler,注意 @Sharable 与无状态;
- 编解码:LengthFieldBasedFrameDecoder + LengthFieldPrepender 解决 TCP 粘包;
- 资源释放:finally 块中 shutdownGracefully(),否则 Linux 下 epoll 句柄泄漏;
- 零拷贝:文件传输时 DefaultFileRegion,但示例可省;
- 日志:内置 LoggingHandler,打开 DEBUG 可观察三次握手、拆包、刷新时机;
- Maven 坐标:io.netty:netty-all:4.1.108.Final(国内阿里云镜像源加速)。
答案
以下代码单文件即可运行,JDK 8+,依赖仅 netty-all,端口 8888。
目录结构:
demo
├── pom.xml
└── src/main/java/io/github/nettydemo/Echo.java
pom.xml 核心片段: <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.108.Final</version> </dependency> </dependencies>
Echo.java: package io.github.nettydemo;
import io.netty.bootstrap.; import io.netty.buffer.; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler;
public final class Echo {
static final int PORT = 8888;
public static void main(String[] args) throws InterruptedException {
startServer();
Thread.sleep(500); // 等服务端绑定端口
startClient();
}
/* ---------- 服务端 ---------- */
private static void startServer() {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast(new LoggingHandler(LogLevel.INFO)) // 观察收发
.addLast(new LengthFieldBasedFrameDecoder(1024,0,4,0,4))
.addLast(new LengthFieldPrepender(4))
.addLast(new EchoServerHandler());
}
});
ChannelFuture f = b.bind(PORT).sync();
System.out.println("Server bind at " + PORT);
f.channel().closeFuture().addListener((ChannelFutureListener) future -> {
boss.shutdownGracefully();
worker.shutdownGracefully();
});
} catch (Exception e) {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
/* ---------- 客户端 ---------- */
private static void startClient() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast(new LoggingHandler(LogLevel.INFO))
.addLast(new LengthFieldBasedFrameDecoder(1024,0,4,0,4))
.addLast(new LengthFieldPrepender(4))
.addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect("127.0.0.1", PORT).sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
/* ---------- 服务端 Handler ---------- */
@ChannelHandler.Sharable
private static class EchoServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
ctx.writeAndFlush(msg.retain()); // echo 回原数据
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
/* ---------- 客户端 Handler ---------- */
private static class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ByteBuf req = Unpooled.wrappedBuffer("hello netty".getBytes());
ctx.writeAndFlush(req);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
byte[] bytes = new byte[msg.readableBytes()];
msg.readBytes(bytes);
System.out.println("Client received: " + new String(bytes));
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
}
运行: mvn package -T1C -DskipTests java -cp target/classes:target/lib/* io.github.nettydemo.Echo
控制台先打印 Server bind at 8888,随后客户端发 hello netty,服务端原样返回,客户端打印 received 后双方优雅退出。
代码行数 <150,但覆盖了线程组、Channel 类型、粘包处理、资源释放、异常回调,可直接粘贴到 IDE 跑通,符合“最小可复现”要求。
拓展思考
-
如果面试官追问“如何压测”:
把客户端改造成连接池 + 固定 QPS 模型,用 ScheduledExecutorService 定时 flush,观测 CPU、线程切换、P99 延迟;
或者直接用 wrk 通过 TCP 自定义脚本压测,对比 Netty 与原生 NIO 的吞吐差异。 -
如果追问“生产环境还要注意什么”:
① 使用 -Dio.netty.allocator.type=pooled 开启堆外内存池,配合 jemalloc 减少 GC 压力;
② 开启 Epoll(Linux)或 IOCP(Windows)native transport,提高 10%+ 性能;
③ 自定义 ChannelOption.TCP_NODELAY、SO_BACKLOG、SO_REUSEADDR,根据业务调优;
④ 利用 Netty 提供的 IdleStateHandler 做心跳,防止防火墙淘汰空闲连接;
⑤ 采用 Fluent API 封装协议指令,避免大量 if-else 分支,提高可维护性。 -
如果让你“再精简”:
可去掉 LengthField* 编解码,改用 DelimiterBasedFrameDecoder,但 TCP 粘包问题仍在,生产慎用;
也可以把服务端和客户端合并到一个 main,用多线程启动,但代码可读性下降,面试不推荐。
记住:最小可复现 ≠ 最小可运行,而是“跑得通、讲得清、扛得住追问”。