Spring Cloud Gateway (七)处理流程解析
简介
初步梳理 Spring Cloud Gateway 的处理流程
过程记录
主要请求流程
在前面的分析中,我们知道在 RoutePredicateHandlerMapping 中是实现了路由查找,于是在这个类中 getHandlerInternal 函数打上断点,通过调用栈向前追溯调用
向前我们追溯到了 DispatcherHandler ,在这个断点处通过断点调试发现有类似循环的操作,这个感觉是查找相应 handler 进行处理,细节部分暂时不够,后面再来详细看
public Mono<Void> handle(ServerWebExchange exchange) {
return this.handlerMappings == null ? this.createNotFoundError() : Flux.fromIterable(this.handlerMappings).concatMap((mapping) -> {
return mapping.getHandler(exchange);
}).next().switchIfEmpty(this.createNotFoundError()).flatMap((handler) -> {
return this.invokeHandler(exchange, handler);
}).flatMap((result) -> {
return this.handleResult(exchange, result);
});
}
在上面函数打断点,再通过调用栈向前查找,找到 netty 相关的一个类: HttpServerHandle 。下面的函数中有类似 Mono 这里的代码,发布后触发调用
public void onStateChange(Connection connection, State newState) {
if (newState == HttpServerState.REQUEST_RECEIVED) {
try {
if (log.isDebugEnabled()) {
log.debug(ReactorNetty.format(connection.channel(), "Handler is being applied: {}"), new Object[]{
this.handler});
}
HttpServerOperations ops = (HttpServerOperations)connection;
// Mono 发布,这一步需要注意,跟踪handler下去
Mono.fromDirect((Publisher)this.handler.apply(ops, ops)).subscribe(ops.disposeSubscriber());
} catch (Throwable var4) {
log.error(ReactorNetty.format(connection.channel(), ""), var4);
connection.channel().close();
}
}