Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement an efficient HTTP Server with Netty

2025-01-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to achieve an efficient HTTP server in Netty". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to achieve an efficient HTTP server in Netty" can help you solve the problem.

1 Overview

HTTP is based on the request / response pattern: the client sends a HTTP request to the server, and the server will return a HTTP response. Netty provides a variety of encoders and decoders to simplify the use of this protocol. An HTTP request / response may consist of multiple data parts, and FullHttpRequest and FullHttpResponse messages are special subtypes that represent the complete request and response, respectively. All types of HTTP messages (FullHttpRequest, LastHttpContent, and so on) implement the HttpObject interface.

(1) HttpRequestEncoder encodes HttpRequest, HttpContent, and LastHttpContent messages into bytes. (2) HttpResponseEncoder encodes HttpResponse, HttpContent, and LastHttpContent messages into bytes. (3) HttpRequestDecoder decodes bytes into HttpRequest, HttpContent, and LastHttpContent messages. (4) HttpResponseDecoder decodes bytes into HttpResponse, HttpContent, and LastHttpContent messages. (5) HttpClientCodec and HttpServerCodec combine request and response. 1.1 aggregate HTTP messages

Since HTTP requests and responses may consist of many parts, you need to aggregate them to form a complete message.

To eliminate this tedious task, Netty provides an aggregator HttpObjectAggregator, which can eliminate multiple

The information part is merged into a FullHttpRequest or FullHttpResponse message. In this way, you will always watch

To the full message content.

1.2 HTTP Compression

When using HTTP, it is recommended that you turn on compression to reduce the size of the transmitted data as much as possible. Although compression will bring

Some overhead on CPU clock cycles, but it's usually a good idea, especially for text data.

say. Netty provides ChannelHandler implementations for compression and decompression, which support both gzip and deflate encoding.

2 Code implementation of 2.1 pom io.netty netty-all 4.1.28.Final junit junit 4.11 org.projectlombok lombok 1.18.20 provided Org.apache.commons commons-lang3 3.12.0 org.apache.commons commons-collections4 4.4 org.slf4j slf4j-api 1.7.21 Commons-logging commons-logging 1.2 org.apache.logging.log4j log4j-api 2.6.2 log4j log4j 1.2.17 true org.slf4j slf4j- Simple 1.7.25 org.apache.maven.plugins maven-compiler-plugin 88 2.2 HttpConstspublic class HttpConsts {private HttpConsts () {} public static final Integer PORT = 8888 Public static final String HOST = "127.0.0.1";} 2.3 server

2.3.1 HttpServer

@ Slf4jpublic class HttpServer {public static void main (String [] args) throws InterruptedException {HttpServer httpServer = new HttpServer (); httpServer.start ();} public void start () throws InterruptedException {EventLoopGroup boss = new NioEventLoopGroup (1); EventLoopGroup worker = new NioEventLoopGroup (); try {ServerBootstrap serverBootstrap = new ServerBootstrap () ServerBootstrap.group (boss, worker) .channel (NioServerSocketChannel.class) .childHandler (new HttpServerHandlerInitial ()); ChannelFuture channelFuture = serverBootstrap.bind (HttpConsts.PORT). Sync (); log.info ("server turned on."); channelFuture.channel (). CloseFuture (). Sync () } finally {boss.shutdownGracefully (); worker.shutdownGracefully ();}

2.3.2 HttpServerBusinessHandler

@ Slf4jpublic class HttpServerBusinessHandler extends ChannelInboundHandlerAdapter {@ Override public void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {/ / parse byteBuf into FullHttpRequest if (msg instanceof FullHttpRequest) {/ / get httpRequest FullHttpRequest httpRequest = (FullHttpRequest) msg; try {/ / get request path, request body, request method String uri = httpRequest.uri () String content = httpRequest.content () .toString (CharsetUtil.UTF_8); HttpMethod method = httpRequest.method (); log.info ("Server received request:"); log.info ("request uri: {}, request content: {}, request method: {}", uri, content, method) / / response String responseMsg = "Hello World"; FullHttpResponse response = new DefaultFullHttpResponse (HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.copiedBuffer (responseMsg,CharsetUtil.UTF_8)); response.headers () .set (HttpHeaderNames.CONTENT_TYPE, "text/plain" Charset=UTF-8 "); ctx.writeAndFlush (response) .addListener (ChannelFutureListener.CLOSE);} finally {httpRequest.release ();}

2.3.3 HttpServerHandlerInitial

Public class HttpServerHandlerInitial extends ChannelInitializer {@ Override protected void initChannel (SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline (); / / http request codec, request decoding, response encoding pipeline.addLast ("serverCodec", new HttpServerCodec ()); / / http request message aggregation into a complete message, the maximum request message is 10m pipeline.addLast ("aggregator", new HttpObjectAggregator (10 * 1024 * 1024)) / / response message compression pipeline.addLast ("compress", new HttpContentCompressor ()); / / Business processing handler pipeline.addLast ("serverBusinessHandler", new HttpServerBusinessHandler ());}} 2.4 client

2.4.1 HttpClient

Public class HttpClient {public static void main (String [] args) throws InterruptedException {HttpClient httpClien = new HttpClient (); httpClien.start ();} public void start () throws InterruptedException {EventLoopGroup eventLoopGroup = new NioEventLoopGroup (); try {Bootstrap bootstrap = new Bootstrap () Bootstrap.group (eventLoopGroup) .channel (NioSocketChannel.class) .handler (new HttpClientHandlerInitial ()); ChannelFuture f = bootstrap.connect (HttpConsts.HOST, HttpConsts.PORT). Sync (); f.channel (). CloseFuture (). Sync ();} finally {eventLoopGroup.shutdownGracefully ();}

2.4.2 HttpClientBusinessHandler

@ Slf4jpublic class HttpClientBusinessHandler extends ChannelInboundHandlerAdapter {@ Override public void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {/ / parses byteBuf into FullHttpResponse if (msg instanceof FullHttpResponse) {FullHttpResponse httpResponse = (FullHttpResponse) msg; HttpResponseStatus status = httpResponse.status (); ByteBuf content = httpResponse.content (); log.info ("client receives response message:") Log.info ("status: {}, content: {}", status, content.toString (CharsetUtil.UTF_8)); httpResponse.release ();} @ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {/ / Encapsulation request information URI uri = new URI ("/ test"); String msg = "Hello" DefaultFullHttpRequest request = new DefaultFullHttpRequest (HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString (), Unpooled.wrappedBuffer (msg.getBytes (CharsetUtil.UTF_8); / / build http request request.headers () .set (HttpHeaderNames.HOST, HttpConsts.HOST); request.headers () .set (HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE) Request.headers () .set (HttpHeaderNames.CONTENT_LENGTH, request.content () .readableBytes ()); / / send http request ctx.writeAndFlush (request);}}

2.4.3 HttpClientHandlerInitial

Public class HttpClientHandlerInitial extends ChannelInitializer {@ Override protected void initChannel (SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline (); / / client encoder, decoder, request encoding, response decoding pipeline.addLast ("clientCodec", new HttpClientCodec ()); / / http aggregator aggregates http requests into a complete message pipeline.addLast ("aggregator", new HttpObjectAggregator (10 * 1024 * 1024)) / / http response decompress pipeline.addLast ("decompressor", new HttpContentDecompressor ()); / / Business handler pipeline.addLast ("clientBusinessHandler", new HttpClientBusinessHandler ());}} this is the end of the introduction on "how Netty implements an efficient HTTP server". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 229

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report