1 引入Netty依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.43.Final</version>
</dependency>
2 编写http服务端
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public void run(){
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpServerCodec())// http 编解码
.addLast("httpAggregator", new HttpObjectAggregator(100 * 1024 * 1024))// http 消息聚合器 512*1024为接收的最大contentlength
.addLast(new HttpServerExpectContinueHandler()).addLast(new HttpServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
System.out.println("服务器开启:"+port);
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new NettyServer(12222).run();
}
}
其中核心代码为 ch.pipeline().addLast(new HttpServerCodec()) .addLast(“httpAggregator”, new HttpObjectAggregator(100 * 1024 * 1024))
作用为添加http请求支持;addLast(new HttpServerHandler())的 HttpServerHandler为http请求具体处理类
核心代码如下:
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
System.out.println(fullHttpRequest.getUri().toString());
if ("/api/test".equals(fullHttpRequest.getUri())) {
{
writeResponse(ctx, false, JSON.toJSONString(ResponseVo.success()).getBytes());
}
} else {
writeResponse(channelHandlerContext, false, JSON.toJSONString(ResponseVo.error()).getBytes());
}
}
private void writeResponse(ChannelHandlerContext ctx, boolean keepAlive, byte[] responseBytes) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); // HttpHeaderValues.TEXT_PLAIN.toString()
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
if (keepAlive) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ctx.writeAndFlush(response);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("Jobs rpc provider netty_http server caught exception", cause);
ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.channel().close(); // close idle channel
logger.debug("Jobs rpc provider netty_http server close an idle channel.");
} else {
super.userEventTriggered(ctx, evt);
}
}
}
这样就可以模拟servlert和tomcat处理http请求了