Netty4+SpringBoot实现http server

一.Netty是什么?

Netty:Netty是 一个异步事件驱动的网络应用程序框架, 用于快速开发可维护的高性能协议服务器和客户端。Netty是一个NIO客户端服务器框架,可以快速轻松地开发协议服务器和客户端等网络应用程序。它极大地简化并简化了TCP和UDP套接字服务器等网络编程。“快速简便”并不意味着最终的应用程序会受到可维护性或性能问题的影响。Netty经过精心设计,具有丰富的协议,如FTP,SMTP,HTTP以及各种二进制和基于文本的传统协议。因此,Netty成功地找到了一种在不妥协的情况下实现易于开发,性能,稳定性和灵活性的方法。来自于官网的描述。

个人理解:是建立在客户端和服务器之间,通过某个指定协议实现网络数据传输,高性能,异步,事件驱动,的java nio框架(协议的容器)。

二.Netty执行流程

图片来源博客:图解Netty5.0https://blog.csdn.net/KouLouYiMaSi/article/details/80589095,侵权删。

三.SpringBoot集成Netty,实现http协议的server服务器端 

1.http协议下的客户端和服务器端的请求执行流程图,图片来源:https://blog.csdn.net/wangshuang1631/article/details/73251180/

2.maven的pom.xml中引入Netty的jar包,添加以下依赖:

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.31.Final</version>
        </dependency>

3.Netty服务端启动器类NettyServer的编码:

package demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * description:
 * author: 
 * date: 2018-11-28 12:07
 **/
@Component
public class NettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
    //boss事件轮询线程组
    private EventLoopGroup boss = new NioEventLoopGroup();
    //worker事件轮询线程组
    private EventLoopGroup worker = new NioEventLoopGroup();

    private Channel channel;

    @Autowired
    ServerChannelInitializer serverChannelInitializer;
    @Value("${n.port}")
    private Integer port;

    /**
     * 开启Netty服务
     *
     * @return
     */
    public ChannelFuture start() {
        //启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)//设置参数,组配置
                .option(ChannelOption.SO_BACKLOG, 128)//socket参数,当服务器请求处理程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。
                .channel(NioServerSocketChannel.class)///构造channel通道工厂//bossGroup的通道,只是负责连接
                .childHandler(serverChannelInitializer);//设置通道处理者ChannelHandler////workerGroup的处理器
        //Future:异步操作的结果
        ChannelFuture channelFuture = serverBootstrap.bind(port);//绑定端口
        ChannelFuture channelFuture1 = channelFuture.syncUninterruptibly();//接收连接
        channel = channelFuture1.channel();//获取通道
        if (channelFuture1 != null && channelFuture1.isSuccess()) {
            log.info("Netty server 服务启动成功,端口port = {}", port);
        } else {
            log.info("Netty server start fail");
        }

        return channelFuture1;
    }

    /**
     * 停止Netty服务
     */
    public void destroy() {
        if (channel != null) {
            channel.close();
        }
        worker.shutdownGracefully();
        boss.shutdownGracefully();
        log.info("Netty server shutdown success");
    }

}

其中@Value("${n.port}")取的是application.properties配置文件中的n.port=7000。

4.通道初始化类ServerChannelInitializer的编码,主要用于设置各种Handler:

package demo.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * description: 通道初始化,主要用于设置各种Handler
 * author: 
 * date: 2018-11-28 14:55
 **/
@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    ServerChannelHandler serverChannelHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //编码解码
        ch.pipeline().addLast(new HttpRequestDecoder());
        ch.pipeline().addLast(new HttpResponseEncoder());

        ch.pipeline().addLast(serverChannelHandler);//ChannelHandler
    }
}

5.通道处理者ServerChannelHandler的编码,就是用来处理请求的:

package demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

/**
 * description:
 * author: 
 * date: 2018-11-28 15:49
 **/
@Component
@ChannelHandler.Sharable
public class ServerChannelHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Netty Server receive msg : " + msg);
        if (msg instanceof HttpRequest) {
            //要返回的内容, Channel可以理解为连接,而连接中传输的信息要为ByteBuf
            ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
            //构造响应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            //设置头信息的的MIME类型
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");  //内容类型
            //设置要返回的内容长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); //内容长度
            //将响应对象返回
            ctx.channel().writeAndFlush(response);
            ctx.close();
        } else {
            System.out.println("the request is not HttpRequest");
        }
    }
    
}

6.最后,SpringBoot启动类中添加Netty的命令行启动:

package demo;

import demo.netty.NettyServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;

/**
 * ClassName: SpringBootApplication
 * description:
 * author: 
 * date: 2018-09-30 09:15
 **/
@org.springframework.boot.autoconfigure.SpringBootApplication//@EnableAutoConfiguration @ComponentScan
public class SpringBootApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class,args);
    }


    @Autowired
    NettyServer nettyServer;

    @Override
    public void run(String... args) throws Exception {
        ChannelFuture start = nettyServer.start();
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                nettyServer.destroy();
            }
        });
        start.channel().closeFuture().syncUninterruptibly();

    }
}

四.启动程序,浏览器访问

1.启动程序后的日志:

2.浏览器访问:127.0.0.1:7000,会看见hello world显示在页面,后端输出:

可以发现,浏览器一次http请求向后端发送了4次请求,原因是一个完整的http请求DefaultFullHttpRequest包含了所有的http请求信息,但实际http请求的时候好像会将http请求行、请求头、请求体分开发送,详细可百度FullHttpRequest(推荐一篇:netty对http协议解析原理解析)。

猜你喜欢

转载自blog.csdn.net/yzh_1346983557/article/details/84769914