在Dubbo的服务发布过程中,Invoker的构造是一个重要的步骤,Invoker代表的是一个可以调用的服务的接口。它的定义如下:
public interface Invoker<T> extends Node {
/**
* get service interface.
*
* @return service interface.
*/
Class<T> getInterface();
/**
* invoke.
*
* @param invocation
* @return result
* @throws RpcException
*/
Result invoke(Invocation invocation) throws RpcException;
}
invoke方法就是代表一次RPC调用,Invocation类代表的是一次调用需要的参数。为了实现通用性,以及实现很多RPC相关的附加功能,在服务端对一个接口实现,不是机械地实现一个Invoker接口,而是实现了一个Invoker的调用链。本文主要就是分析这个调用链是如何构成的。(本文假设读者已经对Dubbo的基本配置和使用有所了解,对涉及到的基础知识不再讲解)
首先是ServiceConfig这个类的doExportUrlsFor1Protocol方法中的一段代码
for (URL registryURL : registryURLs) {
//if protocol is only injvm ,not register
if (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
continue;
}
url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY));
URL monitorUrl = loadMonitor(registryURL);
if (monitorUrl != null) {
url = url.addParameterAndEncoded(MONITOR_KEY, monitorUrl.toFullString());
}
if (logger.isInfoEnabled()) {
logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL);
}
// For providers, this is used to enable custom proxy to generate invoker
String proxy = url.getParameter(PROXY_KEY);
if (StringUtils.isNotEmpty(proxy)) {
registryURL = registryURL.addParameter(PROXY_KEY, proxy);
}
Invoker<?> invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString()));
DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this);
Exporter<?> exporter = protocol.export(wrapperInvoker);
exporters.add(exporter);
}
这个for循环是遍历配置的所有的注册中心,进行服务的发布。下面看循环体的内容,前面的内容主要是对配置进行一些处理,之后到了下面这一行
Invoker<?> invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString()));
这个PROXY_FACTORY定义
/**
* A {@link ProxyFactory} implementation that will generate a exported service proxy,the JavassistProxyFactory is its
* default implementation
*/
private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
这个对象是一个ProxyFactory接口,它获取的是这个接口的AdaptiveExtension对象。关于Dubbo的SPI接口的Adaptive对象,它是一种接口的自适应机制。例如ProxyFactory接口的定义
@SPI("javassist")