Http服务示例演示
启动示例项目
Soul网关源码中提供了各种服务协议的示例项目,放在soul-examples模块下。
示例项目也是SpringBoot项目,我们直接启动SoulTestHttpApplication下的main方法即可。
示例项目启动后,我们登录到Soul网关的后台管理系统,可以看到在divide插件下多了一个http的选择器,也多了一些规则。这些东西怎么来的?带着这个问题我们看一下它的源码。

首先可以找到的是在示例项目的Controller中有如下两个注解,这两个注解中的接口名刚好是我们管理页面中看到的那几个,也就是说我们的Soul网关会自动扫描我们项目中使用这个@SoulSpringMvcClient注解的方法,将其添加到我们的规则中。
@SoulSpringMvcClient(path = "/order")
@SoulSpringMvcClient(path = "/test/**")
接口访问
我们以示例项目中的findByUserId方法,首先访问示例服务器的该方法,可以正常访问。

然后通过网关访问该方法,也是可以访问的,那我们的网关也就配置好了。

当通过网关访问的时候,我们可以看到soul-bootstrap项目控制台输出了如下的log,这就是我们网关的工作,将访问业务系统的接口通过网关代理进行访问。
2021-01-16 00:58:43.382 INFO 13876 --- [-work-threads-3] o.d.soul.plugin.base.AbstractSoulPlugin : divide selector success match , selector name :/http
2021-01-16 00:58:43.382 INFO 13876 --- [-work-threads-3] o.d.soul.plugin.base.AbstractSoulPlugin : divide selector success match , selector name :/http/test/**
2021-01-16 00:58:43.382 INFO 13876 --- [-work-threads-3] o.d.s.plugin.httpclient.WebClientPlugin : The request urlPath is http://192.168.31.146:8188/test/findByUserId?userId=2, retryTimes is 0
根据这个控制台的信息,我们可以定位到服务转发的方法是在这个org.dromara.soul.plugin.httpclient包下的WebClientPlugin类里的execute方法。这里就会根据我们的插件去匹配我们的选择器和规则,然后进行转发。
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
assert soulContext != null;
String urlPath = exchange.getAttribute(Constants.HTTP_URL);
if (StringUtils.isEmpty(urlPath)) {
Object error = SoulResultWrap.error(SoulResultEnum.CANNOT_FIND_URL.getCode(), SoulResultEnum.CANNOT_FIND_URL.getMsg(), null);
return WebFluxResultUtils.result(exchange, error);
}
long timeout = (long) Optional.ofNullable(exchange.getAttribute(Constants.HTTP_TIME_OUT)).orElse(3000L);
int retryTimes = (int) Optional.ofNullable(exchange.getAttribute(Constants.HTTP_RETRY)).orElse(0);
log.info("The request urlPath is {}, retryTimes is {}", urlPath, retryTimes);
HttpMethod method = HttpMethod.valueOf(exchange.getRequest().getMethodValue());
WebClient.RequestBodySpec requestBodySpec = webClient.method(method).uri(urlPath);
return handleRequestBody(requestBodySpec, exchange, timeout, retryTimes, chain);
}
本文介绍Soul网关源码学习的第二篇,重点探讨Http服务示例。启动示例项目,通过注解自动配置Soul网关规则。详细讲解了接口访问流程,包括直接访问和通过网关访问,分析了网关如何根据插件、选择器和规则进行服务转发。
580

被折叠的 条评论
为什么被折叠?



