Netty定义
Netty官网的第一句话就对Netty有了一个清晰的定义:
Netty is an asynchronous event-driven network application
framework.
Netty是以异步事件驱动的网络框架。Netty之所以高效,主要来自于它是如何实现异步事件驱动的:其 I/O 模型和线程处理模型,前者决定如何收发数据,后者决定如何处理数据。
Netty架构
netty架构是基于 Reactor和责任链模式(netty通过popeline将handler组装起来,通过向pipeline里添加handler来监听处理发生的事件)进行设计的。同时设计者在设计时使用了Staged Event Driven Architecture(阶段性的事件驱动架构)的思想,其思路:每个请求分为若干个阶段,每个阶段可以配置不同的线程。
Netty体系结构图
core(核心模块):Extensible Event Model(可扩展的事件模型),Universal Communication API(通用的通讯API),Zero-Copy-Capable Rich Byte Buffer(零拷贝的字节缓冲区)
Transport Services(传输服务): Socket & Datagram,HTTp Tunnel,In-Vm Pipe
Protocol Support(协议支持): HTTP & WebSocket,SSl.StartTLS,Google Protobuf,zlib/gzip Compression,Large File Transfer,RTSP(和流媒体有关),Legacy Text.Binary Protocols with Unit Testability
Netty的一点思考
高性能server要解决的问题
1、异步socket
2、异步IO
3、多协议支持(传输层之上)
4、减少内存碎片
5、减少锁的影响
netty的解决方案
1、使用java的nio,最好是aio(内核直接支持)
2、封装了promise,实现了基于回调的异步io
3、架构上区分了reactor层、pipeline层、协议层和逻辑层, 其协议层支持protobuf, websocket, http等
4、封装了ByteBuf,自己来管理内存,而不是完全依赖jvm 5、单个socket只在一个线程上处理、避免不必要的线程调度开销
一个栗子
public class TestServer{
public static void main(String[] args) throws Exception{
// boss和worker, boss分发给worker
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
childHandler(new TestServerInitializer());
// bind端口号
ChannelFuture channelFuture = serverBootstrap.bind(8788).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 编解码合二为一
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());
}
}
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpMessage) {
ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
ctx.writeAndFlush(response);
}
}
}