Preface introduces

Netty can set up not only Socket services, but also Http and Https services. In this section, we will use a simple introduction to Netty’s Http service that will be used in our future Netty gateway services.

HyperText Transfer Protocol (HTTP) is the most widely used network Protocol on the Internet.

At present, most of them are HTTP services based on Servlet container, and some core subsystems often have very high performance requirements. At this time, we can consider adopting NIO network model to implement HTTP services, so as to improve performance and throughput. Netty is not only convenient for developing network applications, but also has a built-in HTTP codec, so that users can easily develop high-performance HTTP services. By default, Spring Webflux uses Netty.

Environment to prepare

1, jdk1.8 [jdk1.7 can only support part of netty] 2, netty4.1.36. Final [netty3.x 4.x 5] 3, Postman interface debugger, you can download it from the Internet, you can contact me. Bugstack wormhole stack | attention to reply to your email

Code sample

itstack-demo-netty-1-12└ ─ ─ the SRC ├ ─ ─ the main │ └ ─ ─ Java │ └ ─ ─ org.itstack.demo.net ty │ └ ─ ─ server │ ├ ─ ─ MyChannelInitializer. Java │ ├ ─ ─ MyClientHandler. Java │ └ ─ ─ NettyServer. Java └ ─ ─ the test └ ─ ─ Java └ ─ ─ org.itstack.demo.net. Ty test └ ─ ─ ApiTest. JavaCopy the code

Java server/MyChannelInitializer. | add the processing of the Http protocol

/** * wormhole stack: https://bugstack.cn ** * public id: bugstack wormhole stack * Create by fuzhengwei on 2019 */
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) {
        // Data decoding operation
        channel.pipeline().addLast(new HttpResponseEncoder());
        // Data encoding operation
        channel.pipeline().addLast(new HttpRequestDecoder());
        // Add our own implementation of receiving data to the pipe
        channel.pipeline().addLast(newMyServerHandler()); }}Copy the code

Java server/MyClientHandler. | template code has been, and other similar code

/** * wormhole stack: https://bugstack.cn ** * public id: bugstack wormhole stack * Create by fuzhengwei on 2019 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof HttpRequest) {
            DefaultHttpRequest request = (DefaultHttpRequest) msg;
            System.out.println("URI:" + request.getUri());
            System.err.println(msg);
        }

        if (msg instanceof HttpContent) {
            LastHttpContent httpContent = (LastHttpContent) msg;
            ByteBuf byteData = httpContent.content();
            if(! (byteDatainstanceof EmptyByteBuf)) {
                // Receive MSG messages
                byte[] msgByte = new byte[byteData.readableBytes()];
                byteData.readBytes(msgByte);
                System.out.println(new String(msgByte, Charset.forName("UTF-8")));
            }
        }

        String sendMsg = "Wechat public number: BugStack wormhole stack, welcome your attention & access to source code! Extraordinary years eventually come from your daily hard work, every real growth is a choice of life because you see where you are going. Let you and me, Chengyu Zhaoxia, young is just, army horse, engraved elegance. \n" +
                "Blog Stack: https://bugstack.cn\n" +
                "Content introduction: This official account will regularly push scientific and technological information every day; Topics, source code, books, videos, consulting, interviews, environment and other aspects of content. Especially in the technical topics will provide more original content, so that more programmers can start to understand the full picture of the technology from the most basic. "Handwritten RPC Framework", "Implementing JVM with Java", "Full link Monitoring Based on JavaAgent", "Netty Case" and other topics. \n" +
                "Get source code: \n" +
                {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} {bugstack} +
                
      
       \n"
       +
                "{bugstack wormhole stack} public number to obtain source code, reply < RPC source >\n" +
                "{bugStack wormhole stack} public number to obtain source code, reply < JavaAgent-based full link monitoring >";

        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(sendMsg.getBytes(Charset.forName("UTF-8"))));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); cause.printStackTrace(); }}Copy the code

Java server/NettyServer. | template code has been, and other similar code

/** * wormhole stack: https://bugstack.cn ** * public id: bugstack wormhole stack * Create by fuzhengwei on 2019 */
public class NettyServer {

    public static void main(String[] args) {
        new NettyServer().bing(7397);
    }

    private void bing(int port) {
        // Configure the server NIO thread group
        EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)    // Non-blocking mode
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new MyChannelInitializer());
            ChannelFuture f = b.bind(port).sync();
            System.out.println("Itstack-demo-netty server start done. {标 签 : bugstack wormhole stack);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{ childGroup.shutdownGracefully(); parentGroup.shutdownGracefully(); }}}Copy the code

The test results

Start the NettyServer

DecodeResult (decodeResult: success, version: decodeResult (decodeResult: success, version: decodeResult) decodeResult (decodeResult: success, version: decodeResult) HTTP/1.1)
GET / HTTP/1.1
cache-control: no-cache
Postman-Token: 28f37dfb-bb5a-4cb2-ae7a-87cf6cda900c
User-Agent: PostmanRuntime/7.6.0
Accept: */* Host: localhost:7397 accept-encoding: gzip, deflate content-type: multipart/form-data; boundary=--------------------------359056973355668947377349 content-length: 226 Connection: keep-alive ----------------------------359056973355668947377349 Content-Disposition: form-data; Name = "MSG" WeChat number: public bugstack wormhole stack | welcome attention and obtain the source code! ----------------------------359056973355668947377349-- Process finished with exit code -1Copy the code

Postman access; http://localhost:7397 and set the parameters