服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - 如何用Netty实现高效的HTTP服务器

如何用Netty实现高效的HTTP服务器

2021-09-03 11:41你携秋月揽星河丶 Java教程

这篇文章主要介绍了如何用Netty实现高效的HTTP服务器,对HTTP感兴趣的同学可以参考一下

1 概述

HTTP 是基于请求/响应模式的:客户端向服务器发送一个 HTTP 请求,然后服务器将会返回一个 HTTP 响应。Netty 提供了多种编码器和解码器以简化对这个协议的使用。一个HTTP 请求/响应可能由多个数据部分组成,FullHttpRequest 和FullHttpResponse 消息是特殊的子类型,分别代表了完整的请求和响应。所有类型的 HTTP 消息(FullHttpRequest、LastHttpContent 等等)都实现了 HttpObject 接口。

  1. (1) HttpRequestEncoder HttpRequestHttpContent LastHttpContent 消息编码为字节。
  2. (2) HttpResponseEncoder HttpResponseHttpContent LastHttpContent 消息编码为字节。
  3. (3) HttpRequestDecoder 将字节解码为 HttpRequestHttpContent LastHttpContent 消息。
  4. (4) HttpResponseDecoder 将字节解码为 HttpResponseHttpContent LastHttpContent 消息。
  5. (5) HttpClientCodec HttpServerCodec 则将请求和响应做了一个组合。

1.1 聚合 HTTP 消息

由于 HTTP 的请求和响应可能由许多部分组成,因此你需要聚合它们以形成完整的消息。
为了消除这项繁琐的任务,Netty 提供了一个聚合器 HttpObjectAggregator,它可以将多个消
息部分合并为 FullHttpRequest 或者 FullHttpResponse 消息。通过这样的方式,你将总是看
到完整的消息内容。

1.2 HTTP 压缩

当使用 HTTP 时,建议开启压缩功能以尽可能多地减小传输数据的大小。虽然压缩会带
来一些 CPU 时钟周期上的开销,但是通常来说它都是一个好主意,特别是对于文本数据来
说。Netty 为压缩和解压缩提供了 ChannelHandler 实现,它们同时支持 gzip 和 deflate 编码。

2 代码实现

如何用Netty实现高效的HTTP服务器

2.1 pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>io.netty</groupId>
  4. <artifactId>netty-all</artifactId>
  5. <version>4.1.28.Final</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.11</version>
  11. </dependency>
  12. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  13. <dependency>
  14. <groupId>org.projectlombok</groupId>
  15. <artifactId>lombok</artifactId>
  16. <version>1.18.20</version>
  17. <scope>provided</scope>
  18. </dependency>
  19. <!--工具-->
  20. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
  21. <dependency>
  22. <groupId>org.apache.commons</groupId>
  23. <artifactId>commons-lang3</artifactId>
  24. <version>3.12.0</version>
  25. </dependency>
  26. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
  27. <dependency>
  28. <groupId>org.apache.commons</groupId>
  29. <artifactId>commons-collections4</artifactId>
  30. <version>4.4</version>
  31. </dependency>
  32. <!--日志-->
  33. <dependency>
  34. <groupId>org.slf4j</groupId>
  35. <artifactId>slf4j-api</artifactId>
  36. <version>1.7.21</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>commons-logging</groupId>
  40. <artifactId>commons-logging</artifactId>
  41. <version>1.2</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.apache.logging.log4j</groupId>
  45. <artifactId>log4j-api</artifactId>
  46. <version>2.6.2</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>log4j</groupId>
  50. <artifactId>log4j</artifactId>
  51. <version>1.2.17</version>
  52. <optional>true</optional>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.slf4j</groupId>
  56. <artifactId>slf4j-simple</artifactId>
  57. <version>1.7.25</version>
  58. </dependency>
  59. </dependencies>
  60.  
  61. <build>
  62. <plugins>
  63. <plugin>
  64. <groupId>org.apache.maven.plugins</groupId>
  65. <artifactId>maven-compiler-plugin</artifactId>
  66. <configuration>
  67. <source>8</source>
  68. <target>8</target>
  69. </configuration>
  70. </plugin>
  71. </plugins>
  72. </build>

2.2 HttpConsts

  1. public class HttpConsts {
  2.  
  3. private HttpConsts() {
  4.  
  5. }
  6.  
  7. public static final Integer PORT = 8888;
  8.  
  9. public static final String HOST = "127.0.0.1";
  10.  
  11. }

2.3 服务端

2.3.1 HttpServer

  1. @Slf4j
  2. public class HttpServer {
  3.  
  4. public static void main(String[] args) throws InterruptedException {
  5.  
  6. HttpServer httpServer = new HttpServer();
  7. httpServer.start();
  8. }
  9.  
  10. public void start() throws InterruptedException {
  11.  
  12. EventLoopGroup boss = new NioEventLoopGroup(1);
  13. EventLoopGroup worker = new NioEventLoopGroup();
  14.  
  15. try {
  16. ServerBootstrap serverBootstrap = new ServerBootstrap();
  17. serverBootstrap.group(boss, worker)
  18. .channel(NioServerSocketChannel.class)
  19. .childHandler(new HttpServerHandlerInitial());
  20. ChannelFuture channelFuture = serverBootstrap.bind(HttpConsts.PORT).sync();
  21. log.info("服务器已开启......");
  22. channelFuture.channel().closeFuture().sync();
  23. } finally {
  24. boss.shutdownGracefully();
  25. worker.shutdownGracefully();
  26. }
  27.  
  28. }
  29.  
  30. }

2.3.2 HttpServerBusinessHandler

  1. @Slf4j
  2. public class HttpServerBusinessHandler extends ChannelInboundHandlerAdapter {
  3.  
  4. @Override
  5. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  6.  
  7. //通过编解码器把byteBuf解析成FullHttpRequest
  8. if (msg instanceof FullHttpRequest) {
  9.  
  10. //获取httpRequest
  11. FullHttpRequest httpRequest = (FullHttpRequest) msg;
  12.  
  13. try {
  14. //获取请求路径、请求体、请求方法
  15. String uri = httpRequest.uri();
  16. String content = httpRequest.content().toString(CharsetUtil.UTF_8);
  17. HttpMethod method = httpRequest.method();
  18. log.info("服务器接收到请求:");
  19. log.info("请求uri:{},请求content:{},请求method:{}", uri, content, method);
  20.  
  21. //响应
  22. String responseMsg = "Hello World";
  23. FullHttpResponse response = new DefaultFullHttpResponse(
  24. HttpVersion.HTTP_1_1,HttpResponseStatus.OK,
  25. Unpooled.copiedBuffer(responseMsg,CharsetUtil.UTF_8)
  26. );
  27. response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
  28. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  29. } finally {
  30. httpRequest.release();
  31. }
  32.  
  33. }
  34. }
  35. }

2.3.3 HttpServerHandlerInitial

  1. public class HttpServerHandlerInitial extends ChannelInitializer<SocketChannel> {
  2.  
  3. @Override
  4. protected void initChannel(SocketChannel ch) throws Exception {
  5.  
  6. ChannelPipeline pipeline = ch.pipeline();
  7.  
  8. //http请求编解码器,请求解码,响应编码
  9. pipeline.addLast("serverCodec", new HttpServerCodec());
  10. //http请求报文聚合为完整报文,最大请求报文为10M
  11. pipeline.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
  12. //响应报文压缩
  13. pipeline.addLast("compress", new HttpContentCompressor());
  14. //业务处理handler
  15. pipeline.addLast("serverBusinessHandler", new HttpServerBusinessHandler());
  16.  
  17. }
  18. }

2.4 客户端

2.4.1 HttpClient

  1. public class HttpClient {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4.  
  5. HttpClient httpClien = new HttpClient();
  6. httpClien.start();
  7.  
  8. }
  9.  
  10. public void start() throws InterruptedException {
  11. EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
  12. try {
  13. Bootstrap bootstrap = new Bootstrap();
  14. bootstrap.group(eventLoopGroup)
  15. .channel(NioSocketChannel.class)
  16. .handler(new HttpClientHandlerInitial());
  17.  
  18. ChannelFuture f = bootstrap.connect(HttpConsts.HOST, HttpConsts.PORT).sync();
  19. f.channel().closeFuture().sync();
  20.  
  21. } finally {
  22. eventLoopGroup.shutdownGracefully();
  23. }
  24.  
  25. }
  26.  
  27. }

2.4.2 HttpClientBusinessHandler

  1. @Slf4j
  2. public class HttpClientBusinessHandler extends ChannelInboundHandlerAdapter {
  3.  
  4. @Override
  5. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  6. //通过编解码器把byteBuf解析成FullHttpResponse
  7. if (msg instanceof FullHttpResponse) {
  8. FullHttpResponse httpResponse = (FullHttpResponse) msg;
  9. HttpResponseStatus status = httpResponse.status();
  10. ByteBuf content = httpResponse.content();
  11. log.info("客户端接收响应信息:");
  12. log.info("status:{},content:{}", status, content.toString(CharsetUtil.UTF_8));
  13. httpResponse.release();
  14. }
  15. }
  16.  
  17. @Override
  18. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  19.  
  20. //封装请求信息
  21. URI uri = new URI("/test");
  22. String msg = "Hello";
  23. DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
  24. HttpMethod.GET, uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes(CharsetUtil.UTF_8)));
  25.  
  26. //构建http请求
  27. request.headers().set(HttpHeaderNames.HOST, HttpConsts.HOST);
  28. request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  29. request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
  30.  
  31. // 发送http请求
  32. ctx.writeAndFlush(request);
  33. }
  34. }

2.4.3 HttpClientHandlerInitial

  1. public class HttpClientHandlerInitial extends ChannelInitializer<SocketChannel> {
  2.  
  3. @Override
  4. protected void initChannel(SocketChannel ch) throws Exception {
  5.  
  6. ChannelPipeline pipeline = ch.pipeline();
  7.  
  8. //客户端编码、解码器,请求编码,响应解码
  9. pipeline.addLast("clientCodec", new HttpClientCodec());
  10. //http聚合器,将http请求聚合成一个完整报文
  11. pipeline.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
  12. //http响应解压缩
  13. pipeline.addLast("decompressor", new HttpContentDecompressor());
  14. //业务handler
  15. pipeline.addLast("clientBusinessHandler", new HttpClientBusinessHandler());
  16.  
  17. }
  18. }

2.5 测试

启动服务端:

如何用Netty实现高效的HTTP服务器

如何用Netty实现高效的HTTP服务器

启动客户端:

如何用Netty实现高效的HTTP服务器

如何用Netty实现高效的HTTP服务器

以上就是如何用Netty实现高效的HTTP服务器的详细内容,更多关于Netty实现HTTP服务器的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/qq_34125999/article/details/115488543

延伸 · 阅读

精彩推荐