我們用Netty搭建一個簡單的http服務(wù)器省核,來簡單的分析一個Channel的執(zhí)行流程。
我們來新建一個Server
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{
/**
* 死循環(huán) 線程組
* NioEventLoopGroup 是用來處理I/O操作的線程池蕴侧,Netty對 EventLoopGroup 接口針對不同的傳輸協(xié)議提供了不同的實現(xiàn)逐抑。
* 在本例子中瞒爬,需要實例化兩個NioEventLoopGroup羔挡,通常第一個稱為“boss”,
* 用來accept客戶端連接,另一個稱為“worker”匹颤,處理客戶端數(shù)據(jù)的讀寫操作。
*/
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//啟動服務(wù)端的類 ServerBootstrap 是啟動服務(wù)的輔助類托猩,有關(guān)socket的參數(shù)可以通過ServerBootstrap進(jìn)行設(shè)置印蓖。
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)//這里指定NioServerSocketChannel類初始化channel用來接受客戶端請求。
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
建一個Initializer
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
//通常會為新SocketChannel通過添加一些handler京腥,來設(shè)置ChannelPipeline赦肃。
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServiceCodec",new HttpServerCodec());//netty自己的處理器
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;
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
/**
* SpringMVC由容器來判斷http請求是否結(jié)束了 netty可以自己判斷keepalive
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
System.out.println(msg.getClass());
System.out.println(ctx.channel().remoteAddress());
// Thread.sleep(8000);
if (msg instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) msg;
System.out.println("請求方法名:" + httpRequest.method().name());
URI uri = new URI(httpRequest.uri());
if ("/favicon.ico".equals(uri.getPath())) {
System.out.println("請求favicon.ico");
return;
}
//讀取客戶端的請求并返回響應(yīng)
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);
ctx.channel().close();
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channerl active");
super.channelActive(ctx);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelRegistered");
super.channelRegistered(ctx);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded");
super.handlerAdded(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive");
super.channelInactive(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelUnregistered");
super.channelUnregistered(ctx);
}
}
curl 'http://localhost:8899'
handlerAdded 一個新的handler添加 新的通道
channelRegistered 注冊到某個對象
channerl active 連接處于活動狀態(tài)
class io.netty.handler.codec.http.DefaultHttpRequest
/0:0:0:0:0:0:0:1:60290
請求方法名:GET 請求讀取
class io.netty.handler.codec.http.LastHttpContent$1
/0:0:0:0:0:0:0:1:60290
channelInactive 變成不活動狀態(tài)
channelUnregistered 取消注冊
如果使用瀏覽器來請求 http://localhost:8899 則有所不同
handlerAdded
channelRegistered
channerl active
class io.netty.handler.codec.http.DefaultHttpRequest
/0:0:0:0:0:0:0:1:60322
請求方法名:GET
class io.netty.handler.codec.http.LastHttpContent$1
/0:0:0:0:0:0:0:1:60322
class io.netty.handler.codec.http.DefaultHttpRequest
/0:0:0:0:0:0:0:1:60322
請求方法名:GET
請求favicon.ico
class io.netty.handler.codec.http.LastHttpContent$1
/0:0:0:0:0:0:0:1:60322
可以看到并沒有出現(xiàn)
channelInactive
channelUnregistered
當(dāng)我們把瀏覽器關(guān)閉之后,這兩行才出現(xiàn)公浪,這里也體現(xiàn)了Netty并沒有遵循Servlet規(guī)范他宛,需要自己實現(xiàn)。
我們平時的SpringMVC應(yīng)用運行在tomcat之上欠气,與http請求之間的連接由tomcat來保證相應(yīng)的連接斷掉厅各,但是Netty不是這樣的。
- 參考資料
圣思園Netty課程
Netty入門簡介