Dubbo源码分析2-Dubbo SPI 2

计划阅读调试下Dubbo的源码,结合官方源码分析Dubbo,自身再分析总结

本文对应的Dubbo SPI

Dubbo IOC

上一篇讲到SPI,中有一部分没有介绍,在创建扩展类的时候,需要对扩展类进行依赖注入。这里涉及到Dubbo IOC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@SuppressWarnings("unchecked")
private T createExtension(String name) {
// 从配置文件中读取类名,并加载类,初始化到名称-类的表中
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
// 反射创建实例,存入缓存
EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
// 注入依赖,Dubbo IOC部分,通过set方法注入需要的依赖
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
// 循环创建 包装实例
for (Class<?> wrapperClass : wrapperClasses) {
// 用当前的实例作为参数传给后续的包装类作为入参
// 此处的做法涉及到WrapperClass部分
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
type + ") could not be instantiated: " + t.getMessage(), t);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
// 寻找set开头的并且参数只有一个的函数
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
// 获取参数类型
Class<?> pt = method.getParameterTypes()[0];
try {
// 获取参数名称
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
// 寻找此类型和此名称的扩展类
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
// 赋值
method.invoke(instance, object);
}
} catch (Exception e) {
logger.error("fail to inject via method " + method.getName()
+ " of interface " + type.getName() + ": " + e.getMessage(), e);
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return instance;
}

通过setter方法对扩展类依赖注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}

@SuppressWarnings("unchecked")
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null)
throw new IllegalArgumentException("Extension type == null");
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type +
") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
}

ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}

这里objectFactory类型为ExtensionFactory,但是可以在构造函数中看出来,其寻找了ExtensionFactory对应的AdaptiveExtension。AdaptiveExtension表示自适应扩展类(下节介绍)。在Dubbo中ExtensionFactory为AdaptiveExtensionFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {

private final List<ExtensionFactory> factories;

public AdaptiveExtensionFactory() {
// 从缓存中读取ExtensionLoader
ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
// 获取所有的扩展,返回name与class对应关系
for (String name : loader.getSupportedExtensions()) {
list.add(loader.getExtension(name));
}
factories = Collections.unmodifiableList(list);
}

@Override
public <T> T getExtension(Class<T> type, String name) {
// 从
for (ExtensionFactory factory : factories) {
T extension = factory.getExtension(type, name);
if (extension != null) {
return extension;
}
}
return null;
}

}

getSupportedExtensions和SPI部分逻辑一致,获取所有扩展的key值

1
2
3
4
public Set<String> getSupportedExtensions() {
Map<String, Class<?>> clazzes = getExtensionClasses();
return Collections.unmodifiableSet(new TreeSet<String>(clazzes.keySet()));
}

回到最开始,injectExtension依赖注入部分,

1
2
3
4
5
6
 // 寻找此类型和此名称的扩展类
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
// 赋值
method.invoke(instance, object);
}

调用AdaptiveExtensionFactory getExtension 获取到当前所有的ExtensionFactory下对应的名字和类型的扩展类。调用set方法赋值。

Dubbo 自适应扩展类

使用

回到上一章,Dubbo SPI还支持自适应扩展类。

自适应扩展类和普通扩展类的区别在于,自适应扩展类可以根绝URL参数在运行时动态创建扩展类,而不是在启动时创建完毕。

还是参照上一节的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@SPI
public interface Robot {
@Adaptive
void sayHello(URL url);
}

public class Bumblebee implements Robot {

@Override
public void sayHello(URL url) {
System.out.println(this.getClass().getName());
}

}

public class OptimusPrime implements Robot {

@Override
public void sayHello(URL url) {
System.out.println(this.getClass().getName());
}

}

需要自适应扩展类的需要增加@Adaptive注解。@Adaptive注解支持在类和方法上,如果在类上,则不会生成代理类,如果在方法上则会生成代理类。

1
2
3
4
5
6
7
8
9
10
11
public class TestDubbo {

@Test
public void test_adaptive() throws Exception {
ExtensionLoader<Robot> extensionLoader =
ExtensionLoader.getExtensionLoader(Robot.class);
Robot robot = extensionLoader.getAdaptiveExtension();
robot.sayHello(URL.valueOf("test://1.1.1.1:9999?robot=bumblebee"));
robot.sayHello(URL.valueOf("test://1.1.1.1:9999?robot=optimusPrime"));
}
}

robot调用方法则根据URL后的robot=xxx获取对应的扩展类

源码分析

上一节的测试类,首先进入的是 getAdaptiveExtension方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@SuppressWarnings("unchecked")
public T getAdaptiveExtension() {
// 从holder中获取
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
if (createAdaptiveInstanceError == null) {
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
// 两次检查后都没有获取到
try {
instance = createAdaptiveExtension();
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
}
}
}
} else {
throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
}
}

return (T) instance;
}

上面逻辑比较简单,去缓存中获取自适应扩展,获取不到则创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@SuppressWarnings("unchecked")
private T createAdaptiveExtension() {
try {
// 获取到自适应扩展类,并创建新实例的注入依赖
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}

private Class<?> getAdaptiveExtensionClass() {
// 获取所有扩展类
getExtensionClasses();
// 如果找到自适应扩展类,即在类上注解的扩展类,则直接返回了
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
// 如果不是在类上注解的自适应扩展类,需要创建代理类
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}

上面这段逻辑也比较简单,获取到自适应扩展类,并反射创建实例,然后对实例进行依赖注入。

对于在类上的注解,则直接返回,否则需要创建代理类。

1
2
3
4
5
6
7
8
private Class<?> createAdaptiveExtensionClass() {
// 构造代理类代码
String code = createAdaptiveExtensionClassCode();
ClassLoader classLoader = findClassLoader();
com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
// 生成代理类
return compiler.compile(code, classLoader);
}

上面的逻辑即构造代理类代码,并且编译生成代理类。至此,可以看到我们目前用到了两个自适应扩展类,AdaptiveCompiler 和 AdaptiveExtensionFactory。Compiler即是AdaptiveCompiler实现的扩展。这也是Dubbo中唯二的在类上有Adaptive注解的。

上面代码的核心流程在createAdaptiveExtensionClassCode

首先,回到刚才的例子中,在调用

1
robot.sayHello(URL.valueOf("test://1.1.1.1:9999?robot=bumblebee"))时

时,其实是调用了,Robot$Adaptive扩展类中的sayHello方法。Debug之后可以看出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package test.dubbo;
import com.alibaba.dubbo.common.extension.ExtensionLoader;

public class Robot$Adpative implements test.dubbo.Robot {
public void sayHello(com.alibaba.dubbo.common.URL arg0) {
// 如果URL为空则抛出异常
if (arg0 == null) throw new IllegalArgumentException("url == null");
com.alibaba.dubbo.common.URL url = arg0;
// 获取URL参数比如类名为AbcDef则参数key对应abc.def
String extName = url.getParameter("robot");
if(extName == null) throw new IllegalStateException("Fail to get extension(test.dubbo.Robot) name from url(" + url.toString() + ") use keys([robot])");
// 通过此参数获取扩展类,并调用sayHello方法
test.dubbo.Robot extension = (test.dubbo.Robot)ExtensionLoader.getExtensionLoader(test.dubbo.Robot.class).getExtension(extName);extension.sayHello(arg0);
}
}

生成的代理类即以上的内容。结合生成的代理类来看createAdaptiveExtensionClassCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
StringBuilder codeBuilder = new StringBuilder();
Method[] methods = type.getMethods();
boolean hasAdaptiveAnnotation = false;
for (Method m : methods) {
if (m.isAnnotationPresent(Adaptive.class)) {
hasAdaptiveAnnotation = true;
break;
}
}
// no need to generate adaptive class since there's no adaptive method found.
if (!hasAdaptiveAnnotation)
throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!");

codeBuilder.append("package ").append(type.getPackage().getName()).append(";");
codeBuilder.append("\nimport ").append(ExtensionLoader.class.getName()).append(";");
codeBuilder.append("\npublic class ").append(type.getSimpleName()).append("$Adaptive").append(" implements ").append(type.getCanonicalName()).append(" {");

上面代码包含两部分逻辑,首先判断是否有Adaptive注解,如果不存在则报错。之后就是构造代码的package和import语句。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
for (Method method : methods) {
// 方法的基本信息
Class<?> rt = method.getReturnType();
Class<?>[] pts = method.getParameterTypes();
Class<?>[] ets = method.getExceptionTypes();

Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);
StringBuilder code = new StringBuilder(512);
// 如果当前方法不是Adaptive注解的,则直接抛出异常
if (adaptiveAnnotation == null) {
code.append("throw new UnsupportedOperationException(\"method ")
.append(method.toString()).append(" of interface ")
.append(type.getName()).append(" is not adaptive method!\");");
} else {
int urlTypeIndex = -1;
// 如果方法的入参包括了URL类型的参数,记录参数的索引值
for (int i = 0; i < pts.length; ++i) {
if (pts[i].equals(URL.class)) {
urlTypeIndex = i;
break;
}
}
if (urlTypeIndex != -1) {
// 非Null判断
String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");",
urlTypeIndex);
code.append(s);

s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex);
code.append(s);
}
else {
// 如果入参没有直接包含URL类型的参数,寻找参数中包含URL的参数
String attribMethod = null;
LBL_PTS:
for (int i = 0; i < pts.length; ++i) {
Method[] ms = pts[i].getMethods();
for (Method m : ms) {
String name = m.getName();
// 寻找参数中的返回值类型为URL的getter方法
if ((name.startsWith("get") || name.length() > 3)
&& Modifier.isPublic(m.getModifiers())
&& !Modifier.isStatic(m.getModifiers())
&& m.getParameterTypes().length == 0
&& m.getReturnType() == URL.class) {
urlTypeIndex = i;
attribMethod = name;
break LBL_PTS;
}
}
}
if (attribMethod == null) {
throw new IllegalStateException("fail to create adaptive class for interface " + type.getName()
+ ": not found url parameter or url attribute in parameters of method " + method.getName());
}

// Null point check
String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");",
urlTypeIndex, pts[urlTypeIndex].getName());
code.append(s);
s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");",
urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod);
code.append(s);

s = String.format("%s url = arg%d.%s();", URL.class.getName(), urlTypeIndex, attribMethod);
code.append(s);
}

上面的逻辑比较复杂一些,主要是寻找URL。分为两种情况,一种是我们之前例子中的,直接包含URL的,一种是通过入参可以获取到URL的。

例如 com.alibaba.dubbo.common.URL url = arg0.getUrl();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Adaptive注解的value数组
String[] value = adaptiveAnnotation.value();
// 如果没有值,会赋一个默认值,默认值是根据驼峰规则转换来的,例如AaBbCc生成的则是aa.bb.cc
if (value.length == 0) {
char[] charArray = type.getSimpleName().toCharArray();
StringBuilder sb = new StringBuilder(128);
for (int i = 0; i < charArray.length; i++) {
if (Character.isUpperCase(charArray[i])) {
if (i != 0) {
sb.append(".");
}
sb.append(Character.toLowerCase(charArray[i]));
} else {
sb.append(charArray[i]);
}
}
value = new String[]{sb.toString()};
}

// 检查是否存在invocation类型
boolean hasInvocation = false;
for (int i = 0; i < pts.length; ++i) {
if (pts[i].getName().equals("com.alibaba.dubbo.rpc.Invocation")) {
// Null Point check
String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i);
code.append(s);
s = String.format("\nString methodName = arg%d.getMethodName();", i);
code.append(s);
hasInvocation = true;
break;
}
}

// cachedDefaultName即SPI注解值
String defaultExtName = cachedDefaultName;
String getNameCode = null;
for (int i = value.length - 1; i >= 0; --i) {
if (i == value.length - 1) {
if (null != defaultExtName) {
if (!"protocol".equals(value[i]))
if (hasInvocation)
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName);
else
// url中protocol未单独部分,所以需要特殊处理
getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName);
} else {
if (!"protocol".equals(value[i]))
if (hasInvocation)
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
getNameCode = String.format("url.getParameter(\"%s\")", value[i]);
else
// protocol类型特殊处理
getNameCode = "url.getProtocol()";
}
} else {
if (!"protocol".equals(value[i]))
if (hasInvocation)
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);
else
getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);
}
}
code.append("\nString extName = ").append(getNameCode).append(";");

上面的逻辑比较复杂,主要是对URL的处理。一种情况为:

  • 是否有默认值:如果有的话,在最后一个参数的时候需要替换默认值

  • Protocol 其需要从getProtocol方法中获取参数

  • 是否含有Invocation类型,是的话需要从MethodParameter中获取

针对上面的情况

  • 以Protocol接口为例,生成代码如下:
1
2
3
4
5
6
7
8
9
10
11

@SPI("dubbo")
public interface Protocol {
...
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;

@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
...
}
1
String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
  • 以Exchanger为例
1
2
3
4
5
6
7
8
9
10
@SPI(HeaderExchanger.NAME) // header
public interface Exchanger {

@Adaptive({Constants.EXCHANGER_KEY}) // exchanger
ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException;

@Adaptive({Constants.EXCHANGER_KEY})
ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException;

}
1
String extName = url.getParameter("exchanger", "header");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 code.append("\nString extName = ").append(getNameCode).append(";");
// check extName == null?
String s = String.format("\nif(extName == null) " +
"throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");",
type.getName(), Arrays.toString(value));
code.append(s);

// 根据名称获取到扩展类
s = String.format("\n%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);",
type.getName(), ExtensionLoader.class.getSimpleName(), type.getName());
code.append(s);

// return statement
if (!rt.equals(void.class)) {
code.append("\nreturn ");
}

// 调用扩展类相关的代码
s = String.format("extension.%s(", method.getName());
code.append(s);
for (int i = 0; i < pts.length; i++) {
if (i != 0)
code.append(", ");
code.append("arg").append(i);
}
code.append(");");

从URL中拿到扩展类的名字后,获取到相关的扩展类,执行扩展类的函数即可。

之后就是收尾,构造代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
codeBuilder.append("\npublic ").append(rt.getCanonicalName()).append(" ").append(method.getName()).append("(");
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
codeBuilder.append(", ");
}
codeBuilder.append(pts[i].getCanonicalName());
codeBuilder.append(" ");
codeBuilder.append("arg").append(i);
}
codeBuilder.append(")");
if (ets.length > 0) {
codeBuilder.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
codeBuilder.append(", ");
}
codeBuilder.append(ets[i].getCanonicalName());
}
}
codeBuilder.append(" {");
codeBuilder.append(code.toString());
codeBuilder.append("\n}");

至此,Dubbo SPI部分结束了,还是有很多细节需要多Debug才能分别出来