1 、请求入口HttpHandler
自动配置
public class HttpHandlerAutoConfiguration { @Configuration(proxyBeanMethods = false) public static class AnnotationConfig { private final ApplicationContext applicationContext; public AnnotationConfig(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Bean public HttpHandler httpHandler(ObjectProvider<WebFluxProperties> propsProvider) { HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(this.applicationContext).build(); WebFluxProperties properties = propsProvider.getIfAvailable(); if (properties != null && StringUtils.hasText(properties.getBasePath())) { Map<String, HttpHandler> handlersMap = Collections.singletonMap(properties.getBasePath(), httpHandler); return new ContextPathCompositeHandler(handlersMap); } return httpHandler; } } }
这个自动配置与DispatcherServletAutoConfiguration相对应;HttpHandler是WebFlux环境下的核心处理器类。
其中这里的WebHttpHandlerBuilder.applicationContext(this.applicationContext).build()代码就是用来构建HttpWebHandlerAdapter对象。
核心处理类 HttpWebHandlerAdapter。
public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHandler { // 请求入口 public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { if (this.forwardedHeaderTransformer != null) { try { request = this.forwardedHeaderTransformer.apply(request); } catch (Throwable ex) { response.setStatusCode(HttpStatus.BAD_REQUEST); return response.setComplete(); } } ServerWebExchange exchange = createExchange(request, response); // 获取委托类,最终是由委托的WebHandler进行处理 // 1.1 return getDelegate().handle(exchange) .doOnSuccess(aVoid -> logResponse(exchange)) .onErrorResume(ex -> handleUnresolvedError(exchange, ex)) .then(Mono.defer(response::setComplete)); } }
一个请求是如何通过上面的HttpWebHandlerAdapter执行调用处理的?
容器在启动执行refresh核心方法:
public abstract class AbstractApplicationContext { public void refresh() throws BeansException, IllegalStateException { // ... // 执行子类方法 onRefresh(); // ... } } public class ReactiveWebServerApplicationContext { protected void onRefresh() { // ... createWebServer(); // ... } private void createWebServer() { WebServerManager serverManager = this.serverManager; if (serverManager == null) { // ... // this::getHttpHandler方法获取上面的HttpHandler对象 this.serverManager = new WebServerManager(this, webServerFactory, this::getHttpHandler, lazyInit); // ... } initPropertySources(); } protected HttpHandler getHttpHandler() { String[] beanNames = getBeanFactory().getBea