Netty搭建http服务端

╰+攻爆jí腚メ 2022-05-14 04:43 335阅读 0赞

最近一直在看netty的相关资料。现在模拟一个简单的http服务端程序:

  1. package com.xueyou.demo.server;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import io.netty.handler.codec.http.HttpContentCompressor;
  11. import io.netty.handler.codec.http.HttpObjectAggregator;
  12. import io.netty.handler.codec.http.HttpRequestDecoder;
  13. import io.netty.handler.codec.http.HttpResponseEncoder;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. public class HttpServer {
  17. static final Logger LOG = LoggerFactory.getLogger(HttpServer.class);
  18. public static int MAX_CHUNK_SIZE = 1024 * 1024 * 30;
  19. public void bind(int port) throws Exception {
  20. EventLoopGroup bossGroup = new NioEventLoopGroup();
  21. EventLoopGroup workerGroup = new NioEventLoopGroup();
  22. try {
  23. ServerBootstrap b = new ServerBootstrap();
  24. b.group(bossGroup, workerGroup)
  25. .channel(NioServerSocketChannel.class)
  26. .option(ChannelOption.SO_BACKLOG, 1024)
  27. .childHandler(new ChannelInitializer<SocketChannel>() {
  28. @Override
  29. protected void initChannel(SocketChannel socketChannel) throws Exception {
  30. socketChannel.pipeline()
  31. .addLast("http-decoder", new HttpRequestDecoder())
  32. .addLast("http-chunk-aggregator",
  33. new HttpObjectAggregator(HttpServer.MAX_CHUNK_SIZE))
  34. .addLast("http-encoder", new HttpResponseEncoder())
  35. .addLast("compressor", new HttpContentCompressor())
  36. .addLast("handler", new NettyHttpServerHandler());
  37. }
  38. });
  39. ChannelFuture f = b.bind(port).sync();
  40. LOG.info(">>>>>>netty start port:{}<<<<<<", port);
  41. f.channel().closeFuture().sync();
  42. } finally {
  43. bossGroup.shutdownGracefully();
  44. workerGroup.shutdownGracefully();
  45. }
  46. }
  47. public static void main(String[] args) {
  48. int port = 45678;
  49. try {
  50. new HttpServer().bind(port);
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. } finally {
  54. }
  55. }
  56. }
  57. package com.xueyou.demo.server;
  58. import io.netty.buffer.ByteBuf;
  59. import io.netty.buffer.Unpooled;
  60. import io.netty.channel.ChannelFutureListener;
  61. import io.netty.channel.ChannelHandlerContext;
  62. import io.netty.channel.SimpleChannelInboundHandler;
  63. import io.netty.handler.codec.http.*;
  64. import io.netty.util.CharsetUtil;
  65. import org.slf4j.Logger;
  66. import org.slf4j.LoggerFactory;
  67. import org.slf4j.profiler.Profiler;
  68. public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  69. static final Logger LOG = LoggerFactory.getLogger(NettyHttpServerHandler.class);
  70. @Override
  71. protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
  72. Profiler profiler = new Profiler("Timing profiler");
  73. profiler.start("handle request");
  74. LOG.info(fullHttpRequest.getUri());
  75. LOG.info(fullHttpRequest.getMethod().toString());
  76. profiler.start("handle response");
  77. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  78. response.headers().set("content-Type", "text/html;charset=UTF-8");
  79. StringBuilder sb = new StringBuilder();
  80. sb.append("test");
  81. ByteBuf responseBuf = Unpooled.copiedBuffer(sb, CharsetUtil.UTF_8);
  82. response.content().writeBytes(responseBuf);
  83. responseBuf.release();
  84. profiler.start("write response");
  85. channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  86. profiler.stop();
  87. int spentMs = (int) profiler.elapsedTime() / 1000000;
  88. LOG.warn(profiler.toString());
  89. LOG.warn("Total Time is {}ms", spentMs);
  90. }
  91. }

运行后能够使用浏览器或者请求工具进行测试服务端。能够正常返回“test”。

需要注意的是,这里仅仅是一个例子,不能够作为实际的生产环境的服务端,很多问题,比如多线程,文件上传,静态资源,字符转码,获取参数,跨域等等都没有解决。这些都是一些基础的功能。这里不做研究。因为研究的主要目的是为了学习netty,后续我会继续跟进,更新netty学习的进度。

发表评论

表情:
评论列表 (有 0 条评论,335人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Springboot+NettyTCP服务

    Netty是业界最流行的nio框架之一,它具有功能强大、性能优异、可定制性和可扩展性的优点 Netty的优点: 1.API使用简单,开发入门门槛低。 2.功能十分强大,预