spring cloud gateway的核心类DispatcherHandler 这个类就和springmvc的dispatcherHandler的地位是一样的,所有的请求都会经过他。他的主要方法是handler
@Override
public Mono handle(ServerWebExchange exchange) {
if (logger.isDebugEnabled()) {
ServerHttpRequest request = exchange.getRequest();
logger.debug("Processing " + request.getMethodValue() +" request for [" + request.getURI() +"]");
}
if (this.handlerMappings ==null) {
return Mono.error(HANDLER_NOT_FOUND_EXCEPTION);
}
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));
}
关键代码(二)invokeHandler(exchange, handler)
1.invokeHadler里面调用了SimpleHandlerAdapter.handle(exchange, handler)
private Mono invokeHandler(ServerWebExchange exchange, Object handler) {
if (this.handlerAdapters !=null) {
for (HandlerAdapter handlerAdapter :this.handlerAdapters) {
if (handlerAdapter.supports(handler)) {
return handlerAdapter.handle(exchange, handler);
}
}
}
return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
}
2.SimpleHandlerAdapter.handle(exchange, handler)里面又调用了gateway包下面的FilteringWebHandler.handle(ServerWebExchange exchange)方法,在这里面获取了之前放到上下文中的GATEWAY_ROUTE_ATTR,然后获取filters,给所有的过滤器进行排序,然后执行这些过滤器
public Mono handle(ServerWebExchange exchange) {
Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);
List gatewayFilters = route.getFilters();
List combined =new ArrayList<>(this.globalFilters);
combined.addAll(gatewayFilters);
//TODO: needed or cached?
AnnotationAwareOrderComparator.sort(combined);
logger.debug("Sorted gatewayFilterFactories: "+ combined);
return new DefaultGatewayFilterChain(combined).filter(exchange);
}
3.前面初始化的时候,有初始化一个LoadBalancerClientFilter,在这里执行这个filters链的时候有执行这个filter
@Configuration
@ConditionalOnClass({LoadBalancerClient.class, RibbonAutoConfiguration.class, DispatcherHandler.class})
@AutoConfigureAfter(RibbonAutoConfiguration.class)
public class GatewayLoadBalancerClientAutoConfiguration {
// GlobalFilter beans
@Bean
@ConditionalOnBean(LoadBalancerClient.class)
public LoadBalancerClientFilter loadBalancerClientFilter(LoadBalancerClient client) {
return new LoadBalancerClientFilter(client);
}
}
这个就是创建了一个LoadBalancerClientFilter的对象,这个对象中的最主要的方法就是filter(),而filter()中最关键代码就是调用了RibbonLoadBalancerClient.choose(String serviceId)
final ServiceInstance instance =loadBalancer.choose(url.getHost());
下面就是ribbon的源码了
public ServiceInstance choose(String serviceId) {
Server server = getServer(serviceId);
if (server ==null) {
return null;
}
return new RibbonServer(serviceId, server, isSecure(server, serviceId),
serverIntrospector(serviceId).getMetadata(server));
}
这些就是spring cloud gateway 关键流程的源码解析
知识点:
这个在config中有用到单例模式,这个是单例模式的一种应用,一个config被spring容器管理后,默认是单例的,所以在自动加载的时候可以先对该config进行配置的set,然后在被spring管理的其他的类中进行get获取到