Netty-快速入门
----------------------------------------------------
netty是什么?
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
netty是一个异步的事件驱动(不同的阶段,对应不同的回调方法)的网络框架维护着高性能协议的服务器端和客户端的快速开发。
Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.
Netty是一个非阻塞的io客户端服务端的框架可以快速并且简单的开发网络应用比如说客户端和服务端的协议。它极大的简化了网络编程流程比如说tcp或者udp socket服务器。
'Quick and easy' doesn't mean that a resulting application will suffer from a maintainability or a performance issue. Netty has been designed carefully with the experiences earned from the implementation of a lot of protocols such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. As a result, Netty has succeeded to find a way to achieve ease of development, performance, stability, and flexibility without a compromise.
快速和简单并不意味着由此产生的应用程序将要遭受到可维护性或者性能问题的困扰。Netty精简的设计从一些的协议比如说FTP,STMP,HTTP和一些基于二进制的传统协议获取的经验。因此,Netty成功的发现一种方式去实现轻松的开发,性能,稳定和灵妥协。活性而不需要任何的.
特征(Features)
设计
Unified API for various transport types - blocking and non-blocking socket
统一的api基于不同的传输类型-阻塞和非阻塞的socket.
Based on a flexible and extensible event model which allows clear separation of concerns.
基于灵活的可扩展的时间模型,允许明确的关注分离.
Highly customizable thread model - single thread, one or more thread pools such as SEDA
高度可定制的线程模型-单线程,一个或多个线程池比如说SEDA.
SEDA(Staged Event-Driven Architecture)的核心思想是把一个请求处理过程分成几个Stage,不同资源消耗的Stage使用不同数量的线程来处理,Stage间使用事件驱动的异步通信模式。
True connectionless datagram socket support (since 3.1).
真正的无连接的数据报socket支持(基于3.1版本).
使用简单
- Well-documented Javadoc, user guide and examples
详细的用户java文档,用户指南和demo - No additional dependencies, JDK 5 (Netty 3.x) or 6 (Netty 4.x) is enough
不需要额外的依赖,JDK 5 (Netty 3.x版本) 或者 6 (Netty 4.x版本)就足够了 - Note: Some components such as HTTP/2 might have more requirements. Please refer to the Requirements page for more information.
注意:一些组件比如说HTTP/2可能需要一些额外的依赖。
性能
- Better throughput, lower latency
更好的吞吐量,低延迟 - Less resource consumption
资源消耗减少 - Minimized unnecessary memory copy.
不必要的内存拷贝(零拷贝).
安全
Complete SSL/TLS and StartTLS support。
完全的SSl/tls 和 StartTLS的支持。
- 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笔记之二:使用Netty构建http服务
直接看代码:
服务端:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TestServer {
public static void main(String[] args) throws Exception{
//bossGroup是获取连接的,workerGroup是用来处理连接的,这二个线程组都是死循环
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//简化服务端启动的一个类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//group有二个重载方法,一个是接收一个EventLoopGroup类型参数的方法,一个是接收二个EventLoopGroup类型的参数的方法
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).
childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
服务端HttpServerInitializer(初始化连接的时候执行的回调),处理器Handler构成了一个链路
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class TestServerInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//http协议的编解码使用的,是HttpRequestDecoder和HttpResponseEncoder处理器组合
//HttpRequestDecoder http请求的解码
//HttpResponseEncoder http请求的编码
pipeline.addLast("httpServerCodec",new HttpServerCodec());
pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
}
}
服务端Handler,对请求进行路由
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
//浏览器的特性会发送一个/favicon.ico请求,获取网站的图标
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject>{
//channelRead0是读取客户端的请求并且向客户端返回响应的一个方法
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if(msg instanceof HttpRequest){
HttpRequest httpRequest = (HttpRequest)msg;
System.out.println("请求方法名:"+httpRequest.method().name()); //get方法
URI uri = new URI(httpRequest.uri());
//使用浏览器访问localhost:8899会发送二次请求,其中有一次是localhost:8899/favicon.ico,这个url请求访问网站的图标
if("/favicon.ico".equals(uri.getPath())){
System.out.println("请求favicon.ico");
return;
}
//向客户端返回的内容
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);
//其实更合理的close连接应该判断是http1.O还是1.1来进行判断请求超时时间来断开channel连接。
ctx.channel().close();
}
}
}
使用curl命令访问该服务:
➜ curl 'localhost:8899'
hello world%
控制台打印:
请求方法名:GET
相应的使用post,put,delete请求服务
post请求
curl -X post 'localhost:8899'
put请求
curl -X put 'localhost:8899'
delete请求
curl -X delete 'localhost:8899'
我们使用谷歌浏览器访问localhost:8899
,打开开发者工具的时候发现还会请求一次/favicon.ico
(请求当前网站的图标)。此时控制台打印
请求方法名:GET
请求方法名:GET
请求favicon.ico
扩展
我们改造一下TestHttpServerHandler
代码,因为netty是事件驱动的网络框架,我们定义的TestHttpServerHandler
继承SimpleChannelInboundHandler
类,SimpleChannelInboundHandler
类又继承ChannelInboundHandlerAdapter
类,发现ChannelInboundHandlerAdapter
中定义了好多事件回调方法,在不同的事件触发时会执行相应的方法,我们在TestHttpServerHandler
重写这些方法来梳理一下netty的事件回调流程。
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
//浏览器的特性会发送一个/favicon.ico请求,获取网站的图标
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject>{
//channelRead0是读取客户端的请求并且向客户端返回响应的一个方法
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
//io.netty.handler.codec.http.DefaultHttpRequest,io.netty.handler.codec.http.LastHttpContent$1
System.out.println(msg.getClass());
//打印出远程的地址,/0:0:0:0:0:0:0:1: 49734,本地线程的49734端口的线程和netty进行通信
System.out.println(ctx.channel().remoteAddress());
TimeUnit.SECONDS.sleep(8);
if(msg instanceof HttpRequest){
HttpRequest httpRequest = (HttpRequest)msg;
System.out.println("请求方法名:"+httpRequest.method().name()); //get方法
URI uri = new URI(httpRequest.uri());
//使用浏览器访问localhost:8899会发送二次请求,其中有一次是localhost:8899/favicon.ico,这个url请求访问网站的图标
if("/favicon.ico".equals(uri.getPath())){
System.out.println("请求favicon.ico");
return;
}
//向客户端返回的内容
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);
//其实更合理的close连接应该判断是http1.O还是1.1来进行判断请求超时时间来断开channel连接。
ctx.channel().close(