這一節我們來講一下dubbo請求的泛化調用。
dubbo請求到網關后,會進入到ApacheDubboPlugin中,由于dubbo版本的不同,還有一個AlibabaDubboPlugin。我們先看ApachaDubboPlugin,他們邏輯基本相似。
請求來了后,會進入到Dubbo插件
//org.dromara.soul.plugin.apache.dubbo.ApacheDubboPlugin#doExecute
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
//先獲取dubbo的參數
String body = exchange.getAttribute(Constants.DUBBO_PARAMS);
SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
assert soulContext != null;
//獲取元數據
MetaData metaData = exchange.getAttribute(Constants.META_DATA);
//校驗元數據的有效性
if (!checkMetaData(metaData)) {
assert metaData != null;
log.error(" path is :{}, meta data have error.... {}", soulContext.getPath(), metaData.toString());
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
Object error = SoulResultWrap.error(SoulResultEnum.META_DATA_ERROR.getCode(), SoulResultEnum.META_DATA_ERROR.getMsg(), null);
return WebFluxResultUtils.result(exchange, error);
}
//如果元數據的參數列表不為空但是我們的請求body為空,則返回異常
if (StringUtils.isNoneBlank(metaData.getParameterTypes()) && StringUtils.isBlank(body)) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
Object error = SoulResultWrap.error(SoulResultEnum.DUBBO_HAVE_BODY_PARAM.getCode(), SoulResultEnum.DUBBO_HAVE_BODY_PARAM.getMsg(), null);
return WebFluxResultUtils.result(exchange, error);
}
//進行dubbo的泛化調用并返回結果
final Mono<Object> result = dubboProxyService.genericInvoker(body, metaData, exchange);
return result.then(chain.execute(exchange));
}
我們來看一下泛化調用
//org.dromara.soul.plugin.apache.dubbo.proxy.ApacheDubboProxyService#genericInvoker
public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws SoulException {
//從header中獲取DubboTag信息
String dubboTagRouteFromHttpHeaders = exchange.getRequest().getHeaders().getFirst(Constants.DUBBO_TAG_ROUTE);
//如果DubboTag不為空,則放到RpcContext的附件中,用于dubbo傳播中使用
if (StringUtils.isNotBlank(dubboTagRouteFromHttpHeaders)) {
RpcContext.getContext().setAttachment(CommonConstants.TAG_KEY, dubboTagRouteFromHttpHeaders);
}
//獲取dubbo泛化配置
ReferenceConfig<GenericService> reference = ApplicationConfigCache.getInstance().get(metaData.getPath());
//如果獲取為空,則通過initRef獲取
if (Objects.isNull(reference) || StringUtils.isEmpty(reference.getInterface())) {
ApplicationConfigCache.getInstance().invalidate(metaData.getPath());
reference = ApplicationConfigCache.getInstance().initRef(metaData);
}
//通過泛化配置獲取到泛化Service
GenericService genericService = reference.get();
Pair<String[], Object[]> pair;
if (ParamCheckUtils.dubboBodyIsEmpty(body)) {
pair = new ImmutablePair<>(new String[]{}, new Object[]{});
} else {
pair = dubboParamResolveService.buildParameter(body, metaData.getParameterTypes());
}
//泛化異步調用
CompletableFuture<Object> future = genericService.$invokeAsync(metaData.getMethodName(), pair.getLeft(), pair.getRight());
//返回結果
return Mono.fromFuture(future.thenApply(ret -> {
if (Objects.isNull(ret)) {
ret = Constants.DUBBO_RPC_RESULT_EMPTY;
}
exchange.getAttributes().put(Constants.DUBBO_RPC_RESULT, ret);
exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.SUCCESS.getName());
return ret;
})).onErrorMap(exception -> exception instanceof GenericException ? new SoulException(((GenericException) exception).getExceptionMessage()) : new SoulException(exception));
}
重點是如何獲取到泛化配置的. 是通過ApplicationConfigCache.getInstance().initRef(metaData);獲取到。
我們來看下ApplicationConfigCache
//org.dromara.soul.plugin.apache.dubbo.cache.ApplicationConfigCache
public final class ApplicationConfigCache {
private ApplicationConfig applicationConfig;
private RegistryConfig registryConfig;
}
他有兩個dubbo的基本配置,應用配置和注冊中心配置,這兩個配置是為了構造泛化調用所必須的。他通過init方法注入到類中
//org.dromara.soul.plugin.apache.dubbo.cache.ApplicationConfigCache#init
public void init(final DubboRegisterConfig dubboRegisterConfig) {
if (applicationConfig == null) {
applicationConfig = new ApplicationConfig("soul_proxy");
}
if (registryConfig == null) {
registryConfig = new RegistryConfig();
registryConfig.setProtocol(dubboRegisterConfig.getProtocol());
registryConfig.setId("soul_proxy");
registryConfig.setRegister(false);
//這里是我們從dubbo服務注冊的dubbo插件里面的注冊中心,從而能夠保證我們soul網關代理的dubbo服務的注冊中心和我們服務的注冊中心使用同一個,從而能夠保證服務調用通暢
registryConfig.setAddress(dubboRegisterConfig.getRegister());
Optional.ofNullable(dubboRegisterConfig.getGroup()).ifPresent(registryConfig::setGroup);
}
}
init方法調用時機,就是之前我們講的PluginDataHandler調用時機調用的。這里用到ApacheDubboPluginDataHandler
//org.dromara.soul.plugin.apache.dubbo.handler.ApacheDubboPluginDataHandler#handlerPlugin
public void handlerPlugin(final PluginData pluginData) {
if (null != pluginData && pluginData.getEnabled()) {
DubboRegisterConfig dubboRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), DubboRegisterConfig.class);
DubboRegisterConfig exist = Singleton.INST.get(DubboRegisterConfig.class);
if (Objects.isNull(dubboRegisterConfig)) {
return;
}
if (Objects.isNull(exist) || !dubboRegisterConfig.equals(exist)) {
// If it is null, initialize it
ApplicationConfigCache.getInstance().init(dubboRegisterConfig);
ApplicationConfigCache.getInstance().invalidateAll();
}
Singleton.INST.single(DubboRegisterConfig.class, dubboRegisterConfig);
}
}
我們看到,通過維護內存的DubboPlugin插件,從而更新dubbo的配置緩存,并刷新ApplicationConfigCache,dubbo配置緩存。
當我們第一次從緩存中獲取ReferenceConfig的時候,肯定是空的,所以會走到initRef
//org.dromara.soul.plugin.apache.dubbo.cache.ApplicationConfigCache#initRef
public ReferenceConfig<GenericService> initRef(final MetaData metaData) {
try {
//從緩存獲取,不為空直接返回
ReferenceConfig<GenericService> referenceConfig = cache.get(metaData.getPath());
if (StringUtils.isNoneBlank(referenceConfig.getInterface())) {
return referenceConfig;
}
} catch (ExecutionException e) {
log.error("init dubbo ref ex:{}", e.getMessage());
}
//build
return build(metaData);
}
接下來看下build方法
//org.dromara.soul.plugin.apache.dubbo.cache.ApplicationConfigCache#build
public ReferenceConfig<GenericService> build(final MetaData metaData) {
//手動構造ReferenceConfig
ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
reference.setGeneric(true);
//注入applicationConfig
reference.setApplication(applicationConfig);
//注入registryConfig
reference.setRegistry(registryConfig);
//注入serviceName
reference.setInterface(metaData.getServiceName());
reference.setProtocol("dubbo");
//從metaData的rpcExt中獲取額外的信息
String rpcExt = metaData.getRpcExt();
DubboParamExtInfo dubboParamExtInfo = GsonUtils.getInstance().fromJson(rpcExt, DubboParamExtInfo.class);
if (Objects.nonNull(dubboParamExtInfo)) {
//設置dubbo的version
if (StringUtils.isNoneBlank(dubboParamExtInfo.getVersion())) {
reference.setVersion(dubboParamExtInfo.getVersion());
}
//設置dubbo的group
if (StringUtils.isNoneBlank(dubboParamExtInfo.getGroup())) {
reference.setGroup(dubboParamExtInfo.getGroup());
}
//設置負載均衡策略
if (StringUtils.isNoneBlank(dubboParamExtInfo.getLoadbalance())) {
final String loadBalance = dubboParamExtInfo.getLoadbalance();
reference.setLoadbalance(buildLoadBalanceName(loadBalance));
}
//設置url
if (StringUtils.isNoneBlank(dubboParamExtInfo.getUrl())) {
reference.setUrl(dubboParamExtInfo.getUrl());
}
Optional.ofNullable(dubboParamExtInfo.getTimeout()).ifPresent(reference::setTimeout);
Optional.ofNullable(dubboParamExtInfo.getRetries()).ifPresent(reference::setRetries);
}
try {
//通過get獲取代理的對象,如果能夠獲取到,put到cache中
Object obj = reference.get();
if (obj != null) {
log.info("init apache dubbo reference success there meteData is :{}", metaData.toString());
cache.put(metaData.getPath(), reference);
}
} catch (Exception e) {
log.error("init apache dubbo reference ex:{}", e.getMessage());
}
return reference;
}
至此,網關如何實現的dubbo調用就講完了,主要依賴的就是dubbo自己的泛化調用,并通過內存維護dubbo的相關配置,從而構造泛化配置,獲取provider代理,并直接調用