文章目录
概要
上一篇我们介绍了如何使用WebFlux快速的搭建一个请求转发的demo,了解一些基本的概念。这一篇我们来分析soul网关的设计思路,了解soul网关是如何做到将多个插件加载到webflux并进行请求转发的。我们以最简单的divide插件来进行http请求的分析。
我们从以下流程分析整个调用链。
-
一切的开始——SoulConfiguration
-
请求的核心处理入口——SoulWebHandler
-
Http请求插件——WebClientPlugin
-
Http响应处理插件——WebClientResponsePlugin
基础知识
开始之前需要了解,SpringWebFlux的工作原理,不然会很懵逼。
参考:
Soul网关源码阅读(六)—— Soul网关之WebFlux
Soul网关http转发流程分析
SoulConfiguration
以上我们分析了如何将divide插件配置到我们的spring IOC容器,那么我们的soul网关又是如何加载他们到我们的请求处理链中的呢?
我们启动bootstrap服务,控制台打印了以下日志:
可以看到通过SoulConfiguration
配置了类加载了很多不同的插件到Spring服务。
我们的分析就从SoulConfiguration
开始,查看以下代码。
/**
* Init SoulWebHandler.
*
* @param plugins this plugins is All impl SoulPlugin.
* @return {@linkplain SoulWebHandler}
*/
@Bean("webHandler")
public SoulWebHandler soulWebHandler(final ObjectProvider<List<SoulPlugin>> plugins) {
List<SoulPlugin> pluginList = plugins.getIfAvailable(Collections::emptyList);
final List<SoulPlugin> soulPlugins = pluginList.stream()
.sorted(Comparator.comparingInt(SoulPlugin::getOrder)).collect(Collectors.toList());
soulPlugins.forEach(soulPlugin -> log.info("load plugin:[{}] [{}]", soulPlugin.named(), soulPlugin.getClass().getName()));
return new SoulWebHandler(soulPlugins);
}
可以看到这里从上下文中将所有插件对象的集合plugins作为参数参入了SoulWebHandler,使SoulWebHandler具有处理所有插件的能力。
上面分析到SoulConfiguration
配置文件将插件集合plugins配置到了SoulWebHandler
,那么可以断定SoulWebHandler具备了我们网关所有插件的业务处理能力。
SoulWebHandler
查看SoulWebHandler的构造方法:
public final class SoulWebHandler implements WebHandler {
private final List<SoulPlugin> plugins;
private final Scheduler scheduler;
/**
* Instantiates a new Soul web handler.
*
* @param plugins the plugins
*/
public SoulWebHandler(final List<SoulPlugin> plugins) {
this.plugins = plugins;
String schedulerType = System.getProperty("soul.scheduler.type", "fixed");
if (Objects.equals(schedulerType, "fixed")) {
int threads = Integer.parseInt(System.getProperty(
"soul.work.threads", "" + Math.max((Runtime.getRuntime().availableProcessors() << 1) + 1, 16)));
scheduler = Schedulers.newParallel("soul-work-threads", threads