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类的源码解析:Spring Webflux —— 源码阅读之 reactive 包 | 芋道源码 —— 纯源码解析博客

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值