Netty的核心组件与模型
Netty的核心组件包括Channel、EventLoop、ChannelFuture和ChannelHandler。Channel是网络通信的载体,EventLoop负责处理I/O操作,ChannelFuture用于异步操作的结果通知,ChannelHandler处理入站和出站数据。
public class EchoServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoServerHandler());
}
});
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Netty的线程模型
Netty采用Reactor模式,主从多线程模型是常见的选择。主线程组负责接收连接,工作线程组处理I/O操作。这种模型有效利用了多核CPU资源,提高了并发处理能力。
EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 主线程组
EventLoopGroup workerGroup = new NioEventLoopGroup(); // 工作线程组
Netty的零拷贝技术
Netty通过CompositeByteBuf和FileRegion实现了零拷贝。CompositeByteBuf合并多个ByteBuf,避免内存复制;FileRegion直接传输文件内容到网络通道,减少上下文切换和内存拷贝。
FileRegion region = new DefaultFileRegion(
new File("largefile.txt").getChannel(), 0, 1024 * 1024);
channel.writeAndFlush(region);
Netty的编解码器
Netty提供了丰富的编解码器,如StringEncoder/StringDecoder用于字符串处理,Object
442

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



