Netty挖掘机(四)结合spring boot搭建netty脚手架

上文《Netty挖掘机(三)结合spring搭建netty脚手架》,结合Spring+Netty实现API接口服务模块,本文继续码字,以Springboot的方式接入Netty实现API接口服务。

我们知道,spring-boot-starter-web 默认的web容器是Tomcat,同样也支持修改容器

如要把Tomcat 切换为Jetty,我们首先要做的是先移除包中的Tomcat依赖,再加入Jetty容器


    org.springframework.boot
    spring-boot-starter-web
    
        
            spring-boot-starter-tomcat
            org.springframework.boot
        
    


    org.springframework.boot
    spring-boot-starter-jetty

以上操作,即可将默认的Tomcat容器切换为Jetty容器。

然而,当使用Netty替代web容器的时候,也是上面这种做法吗?

回顾下Netty和Servlet的区别

  • Servlet

    Servlet是一种Java EE规范 ,是用Java编写的服务器端程序。其主要功能在于交互式地浏览和修改数据,生成动态Web内容。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。

    Tomcat和Jetty 是一个servlet容器,而Jetty比大多数的servlet容器要更轻,即轻量级的servlet容器。

  • Netty

    而Netty是一个异步事件驱动的基于NIO的网络应用程序框架,它支持扩展实现自己的servlet容器。

当需要面对处理大量网络协议的时候,建议使用Netty,当仅用于HTTP应用程序的时候,可以使用servlet容器。

所以当使用Netty替代tomcat等servlet容器时,可以实现一个自定义的servlet容器。

搭建思路

  1. 首先Springboot 中移除Tomcat 依赖;
  2. 引入Servlet依赖,自己实现一个Servlet上下文,并加入Spring上下文;
  3. Netty捕获到一个完整的Http 请求后,转换为ServletRequest,交给DispatcherServlet处理;
  4. DispatcherServlet内部进行解析, 调用HandlerMapping寻找处理器,找到对应的处理器Controller后执行并返回处理结果;
process.jpg

搭建

Maven pom配置

  • 主要引入了Netty、Springboot的相关依赖,并且排除了内嵌的tomcat包依赖;

  • 项目中使用了Servlet来接收http,而我们又排除了tomcat依赖,所以需手动加上servlet-api依赖;

全局返回实体

@Data
public class ResultVO {
    private Integer result = 0;
    private String msg;
    private String data;
    public static ResultVO create(String data){
        ResultVO ret = new ResultVO();
        ret.setMsg("success");
        ret.setData(data);
        return ret;
    }
}

定义功能类

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/get")
    public ResultVO getUser() {
        return ResultVO.create("my name is jerry");
    }
}

Netty 启动类

通过Spring上下文找到dispatcherServlet,并传入Channel初始化配置类,用于执行具体的业务逻辑。

@Slf4j
@Component
public class HttpServer {

    @Value("${netty.port:8080}")
    private int port;
    @Autowired
    private DispatcherServlet dispatcherServlet;

    static EventLoopGroup boss = new NioEventLoopGroup();
    static EventLoopGroup worker = new NioEventLoopGroup();

    public void start() {
        log.info("############# start server at port: {}... #############", port);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap
                // 绑定两个组
                .group(boss, worker)
                // 创建NioServerSocketChannel实例
                .channel(NioServerSocketChannel.class)
                // 添加Channel初始化配置类
                .childHandler(new HttpChannelInitializer(dispatcherServlet))
                // 服务于boss线程(accept connect)
                // 设置TCP中的连接队列大小,如果队列满了,会发送一个ECONNREFUSED错误信息给C端,即“ Connection refused”
                .option(ChannelOption.SO_BACKLOG, HttpChannelOptionConstants.SO_BACKLOG)
                // 设置关闭tcp的Nagle算法(尽可能发送大块数据,避免网络中充斥着许多小数据块),要求高实时性
                .childOption(ChannelOption.TCP_NODELAY, HttpChannelOptionConstants.TCP_NODELAY)
                // 设置启用心跳保活机制
                .childOption(ChannelOption.SO_KEEPALIVE, HttpChannelOptionConstants.SO_KEEPALIVE);
            bootstrap.bind(port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

管道初始化配置类

每次有请求进来时,调用初始化配置,将处理器添加到管道。

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());
    
    pipeline.addLast(new HttpObjectAggregator(64*1024));

    pipeline.addLast(new HttpFirstServerHandler());
    pipeline.addLast(new HttpLastServerHandler(dispatcherServlet));
}
  • 添加了一个支持最大消息为64*1024 kb大小的HttpFirstServerHandler,即聚合了多个Http片段。而一般不设置的话默认是有多个Http的片段组合成一次请求的;
  • 添加了两个处理器,一个用于将Netty接收到的Http请求包装到HttpServletRequest中,一个用于接收MockHttpServletRequest,并使用dispatcherServlet执行内部的业务逻辑。

包装HttpServletRequest

Netty捕获到一个完整的Http 请求后,转换为ServletRequest,转发到下一个处理器

假设管道配置了聚合http片段时,入站处理器需要继承SimpleChannelInboundHandler

代码如下

public void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    String uri = fullHttpRequest.uri();
    if(uri.indexOf(favicon) >= 0) {
        return;
    }
    uri = URLDecoder.decode(uri, "UTF-8");
    String method = fullHttpRequest.method().name();
    ByteBuf content = fullHttpRequest.content();
    fullHttpRequest.headers().forEach((header) -> servletRequest.addHeader(header.getKey(), header.getValue()));

    UriComponents uriComponents = UriComponentsBuilder.fromUriString(uri).build();
    String path = uriComponents.getPath();
    servletRequest.setRequestURI(uri);
    servletRequest.setServletPath(path);
    servletRequest.setScheme(ofNullable(uriComponents.getScheme()).orElse(null));
    servletRequest.setServerName(ofNullable(uriComponents.getHost()).orElse(null));
    servletRequest.setServerPort(ofNullable(uriComponents.getPort()).orElse(null));

    servletRequest.setMethod(method);
    byte[] byteArr = new byte[content.readableBytes()];
    content.getBytes(content.readerIndex(), byteArr);
    String contentStr = new String(byteArr, "UTF-8");
    servletRequest.setContent(byteArr);
    if(HttpMethod.GET.name().equalsIgnoreCase(method)) {
        QueryStringDecoder uriDecoder = new QueryStringDecoder(uri);
        uriDecoder.parameters().entrySet().stream().forEach(param-> servletRequest.addParameter(param.getKey(), param.getValue().get(0)));
    } else if(HttpMethod.POST.name().equalsIgnoreCase(method)) {
        Map contentMap = new Gson().fromJson(contentStr, new TypeToken>(){}.getType());
        servletRequest.addParameters(contentMap);
    }
    channelHandlerContext.fireChannelRead(servletRequest);
}

处理实际的业务逻辑

DispatcherServlet内部进行解析, 调用HandlerMapping寻找处理器,找到对应的处理器Controller后执行并返回处理结果;

假设管道配置了聚合http片段时,入站处理器需要继承SimpleChannelInboundHandler

protected void channelRead0(ChannelHandlerContext ctx, MockHttpServletRequest servletRequest) throws Exception {
    long startTime = System.currentTimeMillis();

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    dispatcherServlet.service(servletRequest, servletResponse);

    String respContent = servletResponse.getContentAsString();
    ByteBuf resultBuf = Unpooled.copiedBuffer(respContent, CharsetUtil.UTF_8);

    HttpResponseStatus status = HttpResponseStatus.OK;
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, resultBuf);
    // 添加响应头信息
    HttpHeaders headers = response.headers();
    headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON  + "; charset=UTF-8");
    headers.add(HttpHeaderNames.CONTENT_LENGTH, resultBuf.readableBytes());

    ctx.write(response);
    log.info("================= REQUEST END, cost {} ms =================\n", System.currentTimeMillis() - startTime);
}

启动类

public static void main(String[] args) {
    ApplicationContext applicationContext = SpringApplication.run(ServerApplication.class, args);
    applicationContext.getBean(HttpServer.class).start();
}

好了,接下来开始启动程序,发现报错,很明显,描述是指缺少了ServletWebServerFactory这个bean,即未能加载嵌入的供web应用加载的空间。

Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:206)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:154)
    ... 8 common frames omitted

查看源码,可以发现逻辑走向是这样的,

先获取webServer和servletContext,如果两者都为null,则去获取ServletWebServer工厂,进而得到webServer,否则则开始启动上下文。
如果不忽略tomcat,按正常的逻辑跑下去,一般是获取到TomcatServletWebServerFactory再去获得webSever。而且ServletWebServerFactory默认的实现类仅有几种

servletWebServerFactory.jpg

现在我们排除了tomcat的依赖,想要结合Netty自己实现一个Servlet上下文,则需要走else if的逻辑,即可得:servletContext不能为null。

public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext {
    private void createWebServer() {
        WebServer webServer = this.webServer;
        ServletContext servletContext = this.getServletContext();
        if (webServer == null && servletContext == null) {
            // 默认获得Tomcat工厂实现类,用于获取Tomcat作为WebServer
            ServletWebServerFactory factory = this.getWebServerFactory();
            this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
        } else if (servletContext != null) {
            try {
                this.getSelfInitializer().onStartup(servletContext);
            } catch (ServletException var4) {
                throw new ApplicationContextException("Cannot initialize servlet context", var4);
            }
        }

        this.initPropertySources();
    }
}

public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext {
    protected ServletWebServerFactory getWebServerFactory() {
        String[] beanNames = this.getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
        if (beanNames.length == 0) {
            throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.");
        } 
        // ......
    }
}

按以上的分析,由于是在SpringApplication.run的启动逻辑内报错,故我们需要在启动生命周期内,创建ServletContext这个bean

这里可以使用SpringApplicationRunListener,并且通过spring.factories文件配置监听器即可生效

什么是SpringApplicationRunListener

在调用SpringApplication.run()的过程中,会进行初始化事件体系,如果发现有自定义广播,则会将其设置成自身的事件广播,否则使用默认的SimpleApplicationEventMulticaster,代码在org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster

SpringApplicationRunListener接口参与了Springboot的生命周期,开放了基于生命周期各个过程的接口,使得用户方便在指定的生命周期广播相应的事件

创建监听器

public class ServletListener implements SpringApplicationRunListener {

    public ServletListener(SpringApplication application, String[] args) {
        super();
    }
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        class SelfServletContext extends MockServletContext {
            @Override
            public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
                return null;
            }

            @Override
            public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
                return null;
            }
        }
        ServletContext servletContext = new SelfServletContext();
        ((ServletWebServerApplicationContext) context).setServletContext(servletContext);
    }
}

spring.factories

org.springframework.boot.SpringApplicationRunListener=cn.binary.jerry.netty.config.ServletListener

接下来开始启动程序,启动正常,并且调试接口: http://localhost:8082/user/get/jy

发现在最后一个Handler中的dispatcherServlet.service(servletRequest, servletResponse);出错,报空指针...

查看源码发现是在以下代码中,未找到ServletConfig这个配置,而FrameworkServletDispatcherServlet的父类,所以可以通过反射机制给父类的参数配置值

public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware {
    private transient ServletConfig config;
    
    public ServletConfig getServletConfig() {
        return this.config;
    }
    private void publishRequestHandledEvent(HttpServletRequest request, HttpServletResponse response, long startTime, @Nullable Throwable failureCause) {
        if (this.publishEvents && this.webApplicationContext != null) {
            long processingTime = System.currentTimeMillis() - startTime;
            // 由于this.getServletConfig() 为null,获取不到servletName,导致报NPT
            this.webApplicationContext.publishEvent(new ServletRequestHandledEvent(this, request.getRequestURI(), request.getRemoteAddr(), request.getMethod(), this.getServletConfig().getServletName(), WebUtils.getSessionId(request), this.getUsernameForRequest(request), processingTime, failureCause, response.getStatus()));
        }
    }   
}

既然没有配置,我们就手动帮它配,并且进行初始化

public static void main(String[] args) {
    ApplicationContext applicationContext = SpringApplication.run(ServerApplication.class, args);
    // 获取DispatcherServlet
    DispatcherServlet dispatcherServlet = applicationContext.getBean(DispatcherServlet.class);
    CommonUtils.setDeclaredFieldValue(dispatcherServlet, "config", new MockServletConfig());
    try {
        dispatcherServlet.init();
    } catch (ServletException e) {
    }
    applicationContext.getBean(HttpServer.class).start();
}

接下来开始启动程序,启动正常,并且调试接口: http://localhost:8082/user/get/jy ,一切正常了!

注意

在Netty In Action中提到,Server端的程序不建议使用SimpleChannelInboundHandler,因为执行了channelRead0()后会自动释放指向保存该消息的ByteBuf的内存引用,而在Server端往往需要回传数据给Client端,ctx.write()又是异步的,这样就会导致channelRead0()返回后写操作还没有完成。而一般对于Client端使用而言,已经有了传入消息并处理完了,此时便可以自动释放。所以一般开发中Server端的程序的入站处理器建议使用ChannelInboundHandlerAdapter

channelRead_code.jpg

到这里,基于Springboot+Netty实现的API框架已成功搭建好了哈。

具体源码请查看github:

https://github.com/qJerry/Netty-Analyze-Demo/tree/master/Chapter1-3


Ending......

阿黑在下一章节将继续源码剖析!

你可能感兴趣的:(Netty挖掘机(四)结合spring boot搭建netty脚手架)