【发布时间】:2020-09-30 14:21:17
【问题描述】:
一直以为异步执行是为了资源的高效利用和线程的安全,今天却遇到了Netty的奇怪行为。
public class Example {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
try {
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) {
channel.pipeline()
.addLast(new ChannelOutboundHandlerAdapter() {
@Override
public void read(ChannelHandlerContext ctx) {
String id = String.valueOf(Thread.currentThread().getId());
ctx.writeAndFlush(Unpooled.wrappedBuffer(id.getBytes(StandardCharsets.UTF_8)))
.addListener(ChannelFutureListener.CLOSE);
}
});
}
})
.bind("localhost", 1234)
.sync()
.channel()
.closeFuture()
.syncUninterruptibly();
} finally {
group.shutdownGracefully()
.syncUninterruptibly();
}
}
}
当我第一次连接时,我得到了 16。然后是 17、18、19 等等。每个连接都是在一个新线程上执行的!为什么?如果它是多线程的,Netty 的意义何在?
【问题讨论】:
-
唯一的一点是更大的吞吐量。同时服务的客户更多。
-
@AlexeiKaigorodov 为什么?与通常的多线程服务器有什么区别?
-
通常的多线程服务器每个连接花费一个线程。这设置了大约 10000 个同时连接的自然限制。 Netty 是异步的,可以保留更多。