Springboot中一个请求过来的执行过程

有时候我们在springboot中写bean的配置的时候可能会这样写:

@Bean
public WebClient webClient(ApplicationContext applicationContext) {
    String name = applicationContext.getApplicationName();
    System.out.println(name);
    return WebClient.builder().build();
    return null;
}

或者这样写:

@Configuration
public static class AnnotationConfig {
   private ApplicationContext applicationContext;
   public AnnotationConfig(ApplicationContext applicationContext) {
      this.applicationContext = applicationContext;
   }

无论是带有@Configuration注解的类的构造方法,还是@Bean获取bean的方法中,会有一个入参,这个入参其实就是在createBean的时候,从获取的createbeanMethod中取出参数,然后然后从Beanfactory中,找到类型匹配的bean,作为方法入参,执行方法,

解释上面一段的目的是为我们了解webflux处理请求使用的handler打下基础,webflux使用的httpHandler类型是HttpWebHandlerAdapter,创建httpHandler类型的bean在HttpHandlerAutoConfiguration类型的方法中:

@Bean
public HttpHandler httpHandler() {
   return WebHttpHandlerBuilder.applicationContext(this.applicationContext)
         .build();
}

其中build()方法返回的httpHandler类就是HttpWebHandlerAdapter类型。在Spring的onRefresh()方法中

@Override
protected void onRefresh() {
   super.onRefresh();
   try {
      createWebServer();
   }

这个创建的server为webServer类型的NettyWebServer类型

@Override
public WebServer getWebServer(HttpHandler httpHandler) {
   HttpServer httpServer = createHttpServer();
   ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(
         httpHandler);
   return new NettyWebServer(httpServer, handlerAdapter, this.lifecycleTimeout);
}

其中创建ReactorHttpHandlerAdapter使用的httpHandler就是我们上面提到的HttpWebHandlerAdapter。

当一个请求进来的时候,就是通过ReactorHttpHandlerAdapter的apply()方法然后进入了了HttpWebHandlerAdapter类的handle方法中执行了DispatcherHandler的handle方法:

return Flux.fromIterable(this.handlerMappings)
      .concatMap(mapping -> mapping.getHandler(exchange))
      .next()
      .switchIfEmpty(Mono.error(HANDLER_NOT_FOUND_EXCEPTION))
      .flatMap(handler -> invokeHandler(exchange, handler))
      .flatMap(result -> handleResult(exchange, result));

这个方法中,通过RequestMappingHandlerMapping找到对应的HandlerMethod(就是我们Controller中对应的方法),然后执行invokeHandler方法:

private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {
   if (this.handlerAdapters != null) {
      for (HandlerAdapter handlerAdapter : this.handlerAdapters) {
         if (handlerAdapter.supports(handler)) {
            return handlerAdapter.handle(exchange, handler);
         }

选择的HandlerAdapter是RequestMappingHandlerAdapter,在RequestMappingHandlerAdapter方法中执行了InvocableHandlerMethod的invode方法,然后通过反射执行了Controller中的方法。

然后把Controller方法执行的结果,通过DispatcherHandler中的handlerResult方法,返回给外界。

关于DispatcherHandler类的源码解析:http://www.iocoder.cn/Spring-Webflux/lanneng/reactive/

猜你喜欢

转载自blog.csdn.net/lz710117239/article/details/81100221