新聞中心
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 propsProvider) {
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(this.applicationContext).build();
WebFluxProperties properties = propsProvider.getIfAvailable();
if (properties != null && StringUtils.hasText(properties.getBasePath())) {
Map handlersMap = Collections.singletonMap(properties.getBasePath(), httpHandler);
return new ContextPathCompositeHandler(handlersMap);
}
return httpHandler;
}
}
} 這個自動配置與DispatcherServletAutoConfiguration相對應(yīng);HttpHandler是WebFlux環(huán)境下的核心處理器類。

專注于為中小企業(yè)提供成都網(wǎng)站設(shè)計、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)高安免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了上千多家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
其中這里的WebHttpHandlerBuilder.applicationContext(this.applicationContext).build()代碼就是用來構(gòu)建HttpWebHandlerAdapter對象。
核心處理類 HttpWebHandlerAdapter。
public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHandler {
// 請求入口
public Mono 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進(jìn)行處理
// 1.1
return getDelegate().handle(exchange)
.doOnSuccess(aVoid -> logResponse(exchange))
.onErrorResume(ex -> handleUnresolvedError(exchange, ex))
.then(Mono.defer(response::setComplete));
}
} 一個請求是如何通過上面的HttpWebHandlerAdapter執(zhí)行調(diào)用處理的?
容器在啟動執(zhí)行refresh核心方法:
public abstract class AbstractApplicationContext {
public void refresh() throws BeansException, IllegalStateException {
// ...
// 執(zhí)行子類方法
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().getBeanNamesForType(HttpHandler.class);
// ...
return getBeanFactory().getBean(beanNames[0], HttpHandler.class);
}
}(1) 請求處理委托類WebHandler
getDelegate方法返回的調(diào)用的是父類WebHandlerDecorator方法:
public class WebHandlerDecorator implements WebHandler {
private final WebHandler delegate;
public WebHandlerDecorator(WebHandler delegate) {\
this.delegate = delegate;
}
public WebHandler getDelegate() {
return this.delegate;
}
}這里的delegate是誰?
(2) HttpWebHandlerAdapter創(chuàng)建
自動配置
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 propsProvider) {
// 這里通過WebHttpHandlerBuilder對象創(chuàng)建HttpWebHandlerAdapter對象
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(this.applicationContext).build();
// ...
return httpHandler;
}
}
}
public final class WebHttpHandlerBuilder {
private final List filters = new ArrayList<>();
// 獲取WebHttpHandlerBuilder對象
public static WebHttpHandlerBuilder applicationContext(ApplicationContext context) {
// 構(gòu)造WebHttpHandlerBuilder對象,在參數(shù)上會獲取
// 容器中的webHandler名稱的WebHandler對象,
// 而這里獲取的就是DispatcherHandler對象
// 這個對象是如何創(chuàng)建的?
// 1.2.1
WebHttpHandlerBuilder builder = new WebHttpHandlerBuilder(
context.getBean(WEB_HANDLER_BEAN_NAME, WebHandler.class), context);
// 獲取容器中所有的WebFilter類型的Bean對象
List webFilters = context
.getBeanProvider(WebFilter.class)
.orderedStream()
.collect(Collectors.toList());
// 添加到了filters集合中
builder.filters(filters -> filters.addAll(webFilters));
// 獲取容器中所有的WebExceptionHandler類型的異常處理句柄
List exceptionHandlers = context
.getBeanProvider(WebExceptionHandler.class)
.orderedStream()
.collect(Collectors.toList());
builder.exceptionHandlers(handlers -> handlers.addAll(exceptionHandlers));
context.getBeanProvider(HttpHandlerDecoratorFactory.class)
.orderedStream()
.forEach(builder::httpHandlerDecorator);
try {
builder.sessionManager(
context.getBean(WEB_SESSION_MANAGER_BEAN_NAME, WebSessionManager.class));
}catch (NoSuchBeanDefinitionException ex) {
}
try {
builder.codecConfigurer(
context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class));
}catch (NoSuchBeanDefinitionException ex) {
}
try {
builder.localeContextResolver(
context.getBean(LOCALE_CONTEXT_RESOLVER_BEAN_NAME, LocaleContextResolver.class));
} catch (NoSuchBeanDefinitionException ex) {
}
try {
builder.forwardedHeaderTransformer(
context.getBean(FORWARDED_HEADER_TRANSFORMER_BEAN_NAME, ForwardedHeaderTransformer.class));
} catch (NoSuchBeanDefinitionException ex) {
}
return builder;
}
public HttpHandler build() {
// 注意這里將webHandler = DispatcherHandler保存到了
// FilteringWebHandler對象中
WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
// 查看下面的類信息
decorated = new ExceptionHandlingWebHandler(decorated, this.exceptionHandlers);
HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
// ...
return (this.httpHandlerDecorator != null ? this.httpHandlerDecorator.apply(adapted) : adapted);
}
}
// --------------------------------------------------------------------------------
// 上面獲取了WebHttpHandlerBuilder對象后調(diào)用build開始創(chuàng)建
// HttpWebHandlerAdapter對象
public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHandler {
public HttpWebHandlerAdapter(WebHandler delegate) {
super(delegate);
}
}
public class WebHandlerDecorator implements WebHandler {
// 通過上面的源碼,知道了這個
// delegate = ExceptionHandlingWebHandler
private final WebHandler delegate;
public WebHandlerDecorator(WebHandler delegate) {
this.delegate = delegate;
}
public WebHandler getDelegate() {
return this.delegate;
}
}
// -------------------------------------------------------------------------------
public class FilteringWebHandler extends WebHandlerDecorator {
private final DefaultWebFilterChain chain;
// 這里傳遞過來的handler = DispatcherHandler
public FilteringWebHandler(WebHandler handler, List filters) {
super(handler);
// 創(chuàng)建了過濾器鏈
this.chain = new DefaultWebFilterChain(handler, filters);
}
}
public class ExceptionHandlingWebHandler extends WebHandlerDecorator {
private final List exceptionHandlers;
public ExceptionHandlingWebHandler(WebHandler delegate, List handlers) {
// 這里的delegate = FilteringWebHandler
super(delegate);
List handlersToUse = new ArrayList<>();
handlersToUse.add(new CheckpointInsertingHandler());
handlersToUse.addAll(handlers);
this.exceptionHandlers = Collections.unmodifiableList(handlersToUse);
}
} 通過上面的源碼應(yīng)該非常清楚HttpWebHandlerAdapter對象創(chuàng)建的過程及該對象都會寫什么東西。
到此你應(yīng)該清楚了,上面一開始說的getDelegate()方法返回的就是ExceptionHandlingWebHandler對象。
DispatcherHandler創(chuàng)建
public class WebFluxAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(WebProperties.class)
public static class EnableWebFluxConfiguration extends DelegatingWebFluxConfiguration {
}
}在這里的DelegatingWebFluxConfiguration的父類。
WebFluxConfigurationSupport中創(chuàng)建了webHandler名稱的DispatcherHandler對象。
public class WebFluxConfigurationSupport implements ApplicationContextAware {
@Bean
public DispatcherHandler webHandler() {
return new DispatcherHandler();
}
}到此HttpWebHandlerAdapter#handle中執(zhí)行的getDelegate方法返回的是ExceptionHandlingWebHandler對象。
2、 委托類WebHandler執(zhí)行
接下來就是執(zhí)行ExceptionHandlingWebHandler的handle方法了。
public class ExceptionHandlingWebHandler extends WebHandlerDecorator {
private final List exceptionHandlers;
public Mono handle(ServerWebExchange exchange) {
Mono completion;
try {
completion = super.handle(exchange);
} catch (Throwable ex) {
completion = Mono.error(ex);
}
for (WebExceptionHandler handler : this.exceptionHandlers) {
completion = completion.onErrorResume(ex -> handler.handle(exchange, ex));
}
return completion;
}
}
public class WebHandlerDecorator implements WebHandler {
// 通過在上面的build知道該deletgate = FilteringWebHandler
private final WebHandler delegate;
public Mono handle(ServerWebExchange exchange) {
return this.delegate.handle(exchange);
}
}
public class FilteringWebHandler extends WebHandlerDecorator {
private final DefaultWebFilterChain chain;
public FilteringWebHandler(WebHandler handler, List filters) {
// 這個handler = DispatcherHandler對象
super(handler);
this.chain = new DefaultWebFilterChain(handler, filters);
}
@Override
public Mono handle(ServerWebExchange exchange) {
// 執(zhí)行所有的過濾器
return this.chain.filter(exchange);
}
}
public class DefaultWebFilterChain implements WebFilterChain {
private final List allFilters;
@Nullable
private final WebFilter currentFilter;
// handler = DispatcherHandler
private final WebHandler handler;
public DefaultWebFilterChain(WebHandler handler, List filters) {
Assert.notNull(handler, "WebHandler is required");
this.allFilters = Collections.unmodifiableList(filters);
this.handler = handler;
// 這里就是為了讓所有的WebFilter串聯(lián)起來,按照順序執(zhí)行
DefaultWebFilterChain chain = initChain(filters, handler);
this.currentFilter = chain.currentFilter;
this.chain = chain.chain;
}
private static DefaultWebFilterChain initChain(List filters, WebHandler handler) {
// 這里就相當(dāng)于是最后執(zhí)行的一個Chain了,因為第三個參數(shù)(currentFilter) = null
// 在羨慕的filter方法中執(zhí)行的時候判斷了currentFilter如果為空就執(zhí)行DispatcherHandler#handle方法
// 這里大致的流程如下:
DefaultWebFilterChain chain = new DefaultWebFilterChain(filters, handler, null, null);
ListIterator extends WebFilter> iterator = filters.listIterator(filters.size());
while (iterator.hasPrevious()) {
chain = new DefaultWebFilterChain(filters, handler, iterator.previous(), chain);
}
return chain;
}
public Mono filter(ServerWebExchange exchange) {
return Mono.defer(() ->
this.currentFilter != null && this.chain != null ?
invokeFilter(this.currentFilter, this.chain, exchange) :
// 當(dāng)過濾器都執(zhí)行完了以后會執(zhí)行DispatcherHandler調(diào)用
this.handler.handle(exchange));
}
private Mono invokeFilter(WebFilter current, DefaultWebFilterChain chain, ServerWebExchange exchange) {
String currentName = current.getClass().getName();
return current.filter(exchange, chain).checkpoint(currentName + " [DefaultWebFilterChain]");
}
} Webfilter: 1, 2, 3 三個WebFilter。
初始的chain: DefaultWebFilterChain chain = new DefaultWebFilterChain(filters, handler, null, null);
3: chain = DefaultWebFilterChain(filters,handler, 3,chain) 。
2: chain = DefaultWebFilterChain(filters,handler, 2,chain<3>) 。
1: chain = DefaultWebFilterChain(filters,handler, 1,chain<2>) 。
這樣3個過濾器就串聯(lián)在一起了。
WebFilter#filter實現(xiàn): public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { System.out.println("DemoFilter...") ; return chain.filter(exchange) ; } // 過濾器鏈執(zhí)行過程: 1: chain.filter(exchange) ; => currentFilter.filter(exchange, chain) ;(執(zhí)行的是當(dāng)前WebFilter) 執(zhí)行chain#filter,根據(jù)上面此時的chain = chain<2> 2: 依次類推。
3、 DispatcherHandler執(zhí)行
public class DispatcherHandler implements WebHandler {
public Mono handle(ServerWebExchange exchange) {
if (this.handlerMappings == null) {
return createNotFoundError();
}
if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
return handlePreFlight(exchange);
}
return Flux.fromIterable(this.handlerMappings)
.concatMap(mapping -> mapping.getHandler(exchange))
.next()
.switchIfEmpty(createNotFoundError())
.flatMap(handler -> invokeHandler(exchange, handler))
.flatMap(result -> handleResult(exchange, result));
}
} 其實接下來的過程就和Spring WebMVC的執(zhí)行大致相同。
- 查找HandlerMapping。
- 查找HandlerAdapter。
- 查找HandlerResultHandler。
通過HandlerAdapter調(diào)用處理程序的返回值被包裝為HandlerResult,并傳遞給聲稱支持它的第一個HandlerResultHandler。下表顯示了可用的HandlerResultHandler實現(xiàn),所有這些實現(xiàn)都在WebFlux配置中聲明:
4、 流程處理
新聞名稱:一文帶你徹底理解SpringWebFlux的工作原理
本文URL:http://m.5511xx.com/article/dhoppeg.html


咨詢
建站咨詢
