dubbo是一款开源的高性能Java RPC框架,可以像调用本地函数一样,调用远程服务。下面对dubbo服务引用部分的源码进行分析, 以dubbo-demo-xml为例进行说明, 版本为2.7.6-SNAPSHOT,不同版本之间代码会有细微差别,但是核心思想是一致的。学习dubbo源码最好的方式是将demo代码运行起来,然后调试去看。
主要代码有:
Application.java
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
context.start();
DemoService demoService = context.getBean(DemoService.class);
CompletableFuture<String> hello = demoService.sayHelloAsync("world");
System.out.println("result: " + hello.get());
dubbo-consumer.xml
<dubbo:application name="demo-consumer"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:reference id="demoService" check="false" interface="org.apache.dubbo.demo.DemoService"/>
dubbo服务的引用主要包括:
- 服务(DemoService)的BeanDefinition的初始化
加载并解析配置(dubbo-consumer.xml),然后生成DemoService的BeanDefinition,注册到到IoC容器的beanDefinitionMap中 - 服务的实例化(DemoService的实例化)
当根据DemoService查找其实现时,会根据demoService去beanDefinitionMap中查找定义,这里是ReferenceBean,又因为ReferenceBean实现了FactoryBean接口,所以会调用FactoryBean#getObject方法实例化
1 BeanDefinition的初始化
AbstractRefreshableApplicationContext#refreshBeanFactory
-> AbstractXmlApplicationContext#loadBeanDefinitions(DefaultListableBeanFactory)
->AbstractXmlApplicationContext#loadBeanDefinitions(XmlBeanDefinitionReader)
->AbstractBeanDefinitionReader#loadBeanDefinitions(String...)
->AbstractBeanDefinitionReader#loadBeanDefinitions(String, jSet<Resource>)
-> XmlBeanDefinitionReader#loadBeanDefinitions(EncodedResource)
->XmlBeanDefinitionReader#doLoadBeanDefinitions
-> XmlBeanDefinitionReader#registerBeanDefinitions
->DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions
-> DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
-> BeanDefinitionParserDelegate#parseCustomElement(Element, BeanDefinition)
经过长长的调用链,最终调用的是
public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
String namespaceUri = getNamespaceURI(ele);
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
其中this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri) 会调用DubboNamespaceHandler对dubbo的xml配置进行解析,DubboNamespaceHandler#init会执行如下代码,将xml中的dubbo:reference和ReferenceBean关联起来
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
最终IoC容器中,beanDefinitionMap中demoService对应的是ReferenceBean是, 这也就解释了为什么根据类型(DemoService)查找其实现时,调用的是ReferenceBean的getObject方法
2. 服务引用
Dubbo服务引用的时机有两个,
- 在 Spring 容器调用 ReferenceBean 的 afterPropertiesSet 方法时引用服务,需要配置 <dubbo:reference> 的 init 属性开启
- 第二个是在 ReferenceBean 对应的服务被注入到其他类中时引用,默认情况。
其实主要看ReferenceBean#getObject的调用时机, getObject是服务引用的入口:
ReferenceBean#getObject
-> ReferenceConfig#get
-> ReferenceConfig#init
-> ReferenceConfig#createProxy
createProxy中的主要代码如下, 包括创建invoker和创建代理两步。
// 创建invoker
invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0))
// 创建服务代理
return (T) PROXY_FACTORY.getProxy(invoker, ProtocolUtils.isGeneric(generic))
2.1 创建invoker
Invoker 是 Dubbo 的核心模型,代表一个可执行体。在服务提供方,Invoker 用于调用服务提供类。在服务消费方,Invoker 用于执行远程调用。
invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0))
REF_PROTOCOL是 Protocol$Adaptive, url.get(0).getProtocol为"registry" 所以首先调用的ProtocolListenerWrapper(ProtocolFilterWrapper(RegistryProtocol))#refer, RegistryProtocol的#refer 内部调用ProtocolListenerWrapper(ProtocolFilterWrapper(DubboProtocol))#refer
- ProtocolListenerWrapper(ProtocolFilterWrapper(RegistryProtocol))#refer 只是单纯地调用RegistryProtocol#refer
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
url = getRegistryUrl(url);
Registry registry = registryFactory.getRegistry(url);
return doRefer(cluster, registry, type, url);
}
registryFactory.getRegistry(url); 根据key从全局的注册中心集合中获取注册中心, 如果没有则创建
key为:zookeeper://127.0.0.1:2181/com.alibaba.dubbo.registry.RegistryService
最终registry为: ZookeeperRegistry:
zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=demo-consumer&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=60701&qos.port=33333×tamp=1597565872457
doRefer 包括注册服务消费者,即在zookeeper的consumers目录下新建节点, 从注册中心获取可用的服务提供者,通过netty建立连接。 最终得到的invoker对象如下:
2.2 创建代理
DemoService demoService = context.getBean(DemoService.class) 获得的是由proxyFactory.getProxy(invoker) 生成的代理对象
这样demoService对sayHelloAsync的调用,就可以变成对invoker的调用
通过ProxyGenerator,得到代理对象demoService的字节码,最终生成的代理对象为(去掉不相关的hashCode、equals、toString):
public final class proxy0 extends Proxy implements DC, Destroyable, EchoService, DemoService {
private static Method m4;
private static Method m6;
private static Method m5;
private static Method m3;
public proxy0(InvocationHandler var1) throws {
super(var1);
}
public final Object $echo(Object var1) throws {
try {
return (Object)super.h.invoke(this, m4, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String sayHello(String var1) throws {
try {
return (String)super.h.invoke(this, m6, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final CompletableFuture sayHelloAsync(String var1) throws {
try {
return (CompletableFuture)super.h.invoke(this, m5, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void $destroy() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m4 = Class.forName("com.alibaba.dubbo.rpc.service.EchoService").getMethod("$echo", Class.forName("java.lang.Object"));
m6 = Class.forName("org.apache.dubbo.demo.DemoService").getMethod("sayHello", Class.forName("java.lang.String"));
m5 = Class.forName("org.apache.dubbo.demo.DemoService").getMethod("sayHelloAsync", Class.forName("java.lang.String"));
m3 = Class.forName("org.apache.dubbo.rpc.service.Destroyable").getMethod("$destroy");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
参考:
http://dubbo.apache.org/zh-cn/docs/source_code_guide/refer-service.html