Dubbo系列(二)源碼分析之SPI機制
在閱讀Dubbo源碼時,常常看到
ExtensionLoader.getExtensionLoader(*.class).getAdaptiveExtension();
ExtensionLoader.getExtensionLoader(*.class).getExtension(“name”);
那麼需要深入瞭解dubbo,瞭解SPI源碼是必不可少的過程
下面根據dubbo 2.5.4進行源碼分析
ps.由於源碼分析過程不便於分段落,很容易混亂,需要根據源碼信息一步一步追蹤。
萬惡之源——SPI入口
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if(type == null) {
throw new IllegalArgumentException("Extension type == null");
} else if(!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
} else if(!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type + ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
} else {
ExtensionLoader loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
if(loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type));
loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
}
return loader;
}
}
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type));
調用了構造器方法,並置入EXTENSION_LOADERS,那麼EXTENSION_LOADERS可以推測出是一個容器,用來保存ExtensionLoader信息,不必每次都new,而便於調用。
private ExtensionLoader(Class<?> type) {
this.type = type;
this.objectFactory = type == ExtensionFactory.class?null:(ExtensionFactory)getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension();
}
那麼就需要明白ExtensionLoader這個類實例化對象是用來幹什麼的,首先我們知道EXTENSION_LOADERS是用來保存type-ExtensionLoader信息的map,type是接口類類型,那麼很容易聯想到ExtensionLoader對象則是用來爲該接口類生產不同用戶所需的實現類的。
開始驗證猜想:type是接口類類型,ExtensionLoader對象是用來爲該接口類生產不同用戶所需的實現類的。
從ExtensionLoader.getExtensionLoader(*.class).getAdaptiveExtension();
入手,看看是如何獲取真正的實現類的。
getExtensionLoader(type)
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if(type == null) {
throw new IllegalArgumentException("Extension type == null");
} else if(!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
} else if(!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type + ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
} else {
ExtensionLoader loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
if(loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type));
loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
}
//最終返回一個EXTENSION_LOADERS已存在或新創建的new ExtensionLoader(type)對象
return loader;
}
}
new ExtensionLoader(type)
private ExtensionLoader(Class<?> type) {
//實例化對象有兩個屬性,1.type 2.objectFactory
this.type = type;
//objectFactory過濾了ExtensionFactory.class,那麼進入:後面的語句
this.objectFactory = type == ExtensionFactory.class?null:(ExtensionFactory)getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension();
}
(ExtensionFactory)getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension();
(ExtensionFactory)getExtensionLoader(ExtensionFactory.class)
是不是有熟悉的感覺
此時傳入的類型爲ExtensionFactory
,調用方式與開場白沒有區別!
那麼再次猜想:ExtensionFactory
是用來生產Extension的類,且也是通過SPI的方式獲得的擴展類。
(Extension
是用來生產擴展類具體實現類的類,可能會有一點繞,不過對比spring中的beanFactory
和FactoryBean
還是比較好理解的。)
現在終於要進入getAdaptiveExtension()
方法了
getAdaptiveExtension()
public T getAdaptiveExtension() {
//從緩存獲取默認實現類
Object instance = this.cachedAdaptiveInstance.get();
if(instance == null) {
if(this.createAdaptiveInstanceError != null) {
throw new IllegalStateException("fail to create adaptive instance: " + this.createAdaptiveInstanceError.toString(), this.createAdaptiveInstanceError);
}
Holder var2 = this.cachedAdaptiveInstance;
//使用雙重檢查來實例化
synchronized(this.cachedAdaptiveInstance) {
instance = this.cachedAdaptiveInstance.get();
if(instance == null) {
try {
//實例化的方法
instance = this.createAdaptiveExtension();
this.cachedAdaptiveInstance.set(instance);
} catch (Throwable var5) {
this.createAdaptiveInstanceError = var5;
throw new IllegalStateException("fail to create adaptive instance: " + var5.toString(), var5);
}
}
}
}
return instance;
}
繼續進入createAdaptiveExtension()
private T createAdaptiveExtension() {
try {
return this.injectExtension(this.getAdaptiveExtensionClass().newInstance());
} catch (Exception var2) {
throw new IllegalStateException("Can not create adaptive extenstion " + this.type + ", cause: " + var2.getMessage(), var2);
}
}
繼續進入this.injectExtension(this.getAdaptiveExtensionClass().newInstance());
那麼有兩個過程,1.實例化對象 2.inject依賴注入 ,類似spring的依賴注入過程,畢竟bean都是由spring管理的
newInstance()就不深入看了,簡單介紹就是通過反射的方式獲取到第一個public構造器,並調用instance()方法進行該type 默認實現類的實例化。
爲了驗證是默認實現類,進入getAdaptiveExtensionClass()
private Class<?> getAdaptiveExtensionClass() {
this.getExtensionClasses();
return this.cachedAdaptiveClass != null?this.cachedAdaptiveClass:(this.cachedAdaptiveClass = this.createAdaptiveExtensionClass());
}
記住return的對象是cachedAdaptiveClass
或createAdaptiveExtensionClass()
繼續getExtensionClasses();
private Map<String, Class<?>> getExtensionClasses() {
//這裏緩存的是已加載類的類型
Map classes = (Map)this.cachedClasses.get();
if(classes == null) {
Holder var2 = this.cachedClasses;
synchronized(this.cachedClasses) {
classes = (Map)this.cachedClasses.get();
if(classes == null) {
//加載擴展類
classes = this.loadExtensionClasses();
this.cachedClasses.set(classes);
}
}
}
return classes;
}
繼續深入loadExtensionClasses();
private Map<String, Class<?>> loadExtensionClasses() {
//回憶起猜想:默認
//獲取SPI註解
SPI defaultAnnotation = (SPI)this.type.getAnnotation(SPI.class);
if(defaultAnnotation != null) {
String extensionClasses = defaultAnnotation.value();
if(extensionClasses != null && (extensionClasses = extensionClasses.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(extensionClasses);
if(names.length > 1) {
throw new IllegalStateException("more than 1 default extension name on extension " + this.type.getName() + ": " + Arrays.toString(names));
}
if(names.length == 1) {
//緩存從SPI註解中獲取的默認實現類名
this.cachedDefaultName = names[0];
}
}
}
HashMap extensionClasses1 = new HashMap();
//按照dubbo SPI規範加載這三個路徑下的文件,並加入到extensionClasses1這個map中
this.loadFile(extensionClasses1, "META-INF/dubbo/internal/");
this.loadFile(extensionClasses1, "META-INF/dubbo/");
this.loadFile(extensionClasses1, "META-INF/services/");
return extensionClasses1;
}
return extensionClasses1回溯後發現,此時這三個路徑下的文件中配置的實現類都加載到cachedClasses中,且使得cachedDefaultName中有了值,作爲默認實現類。
此時進入createAdaptiveExtensionClass()
private Class<?> createAdaptiveExtensionClass() {
//生成代碼
String code = this.createAdaptiveExtensionClassCode();
//獲得類加載器
ClassLoader classLoader = findClassLoader();
//獲得編譯器
Compiler compiler = (Compiler)getExtensionLoader(Compiler.class).getAdaptiveExtension();
//獲得編譯後的類
return compiler.compile(code, classLoader);
}
這裏則是實例化實現類的核心方法了
可見,實例化實現類的核心方法首先是通過代碼寫代碼!
那麼生成的類是什麼樣的呢?
以protocol爲例,最終生成Protocol$Adaptive類:
public class Protocol$Adaptive implements com.alibaba.dubbo.rpc.Protocol {
public void destroy() {
throw new UnsupportedOperationException("method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
}
public int getDefaultPort() {
throw new UnsupportedOperationException("method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
}
public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {
if (arg1 == null) throw new IllegalArgumentException("url == null");
com.alibaba.dubbo.common.URL url = arg1;
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
return extension.refer(arg0, arg1);
}
public com.alibaba.dubbo.rpc.Exporter export(com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.RpcException {
if (arg0 == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null");
if (arg0.getUrl() == null)
throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null");
com.alibaba.dubbo.common.URL url = arg0.getUrl();
//SPI中配置項爲"dubbo",所以這裏編譯出來的默認值爲dubbo
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
return extension.export(arg0);
}
}
難受的是,我們發現裏面依然嵌套了一層extension的調用模式,說明這個類依然是一個代理類!
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
不過不一樣的是,這裏調用的方法是getExtension(extName)
,不要着急,終於到了最終實例化的時候了:
再次回到ExtensionLoader.getExtension(name)
方法
public T getExtension(String name) {
if(name != null && name.length() != 0) {
if("true".equals(name)) {
return this.getDefaultExtension();
} else {
//又是各種緩存
Holder holder = (Holder)this.cachedInstances.get(name);
if(holder == null) {
this.cachedInstances.putIfAbsent(name, new Holder());
holder = (Holder)this.cachedInstances.get(name);
}
Object instance = holder.get();
if(instance == null) {
synchronized(holder) {
instance = holder.get();
if(instance == null) {
//終於找到你了,真正的實例化方法!
instance = this.createExtension(name);
holder.set(instance);
}
}
}
return instance;
}
} else {
throw new IllegalArgumentException("Extension name == null");
}
}
進入最終的實例化方法createExtension(String name)
private T createExtension(String name) {
//刷新緩存的已知實現類
Class clazz = (Class)this.getExtensionClasses().get(name);
if(clazz == null) {
throw this.findException(name);
} else {
try {
//從已經實例化過的緩存map中獲取
Object t = EXTENSION_INSTANCES.get(clazz);
if(t == null) {
//實例化並放入緩存
EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
t = EXTENSION_INSTANCES.get(clazz);
}
//爲t進行依賴注入
this.injectExtension(t);
Set wrapperClasses = this.cachedWrapperClasses;
Class wrapperClass;
//注入給該t的wrapepr
if(wrapperClasses != null && wrapperClasses.size() > 0) {
for(Iterator var5 = wrapperClasses.iterator(); var5.hasNext(); t = this.injectExtension(wrapperClass.getConstructor(new Class[]{this.type}).newInstance(new Object[]{t}))) {
wrapperClass = (Class)var5.next();
}
}
return t;
} catch (Throwable var7) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " + this.type + ") could not be instantiated: " + var7.getMessage(), var7);
}
}
}
最終返回一個可能進行wrapper包裝過的對象!
終於實例化結束,跳出實例化的過程,回到injectExtension()
是不是覺得奇怪,前面在實例化的過程中已經進行了injectExtension()的操作
其實,這裏進行注入的對象應該是Protocol$Adaptive,這個動態代理對象!
injectExtension()注入過程
private T injectExtension(T instance) {
try {
if(this.objectFactory != null) {
Method[] e = instance.getClass().getMethods();
int var3 = e.length;
for(int var4 = 0; var4 < var3; ++var4) {
Method method = e[var4];
//啥也別看了,看到set了,可以猜想到通過調用set方法進行注入
if(method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers())) {
//獲取set方法的第一個參數類型
Class pt = method.getParameterTypes()[0];
try {
String e1 = method.getName().length() > 3?method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4):"";
//從objectFactory獲取擴展類(依賴的某個接口類)
//objectFactory前面瞭解到,是ExtensionFactory的擴展類,用來生產擴展類
Object object = this.objectFactory.getExtension(pt, e1);
if(object != null) {
//注入
method.invoke(instance, new Object[]{object});
}
} catch (Exception var9) {
logger.error("fail to inject via method " + method.getName() + " of interface " + this.type.getName() + ": " + var9.getMessage(), var9);
}
}
}
}
} catch (Exception var10) {
logger.error(var10.getMessage(), var10);
}
return instance;
}
return instance,回溯到getAdaptiveExtension()
,最終getAdaptiveExtension()返回一個由objectFactory生產的實例化且進行依賴注入了的默認擴展類。
稍微整理一下調用鏈路:
前文中的兩個調用鏈最終生產的對象應該一目瞭然了:
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
最終獲得的對象爲Protocol$Adaptive,且該對象是一個代理對象,最終調用的對象依然是ProtocolFilterWrapper(ProtocolListenerWrapper({extName}Protocol)),extName默認值爲SPI註解中的值,這裏是dubbo。ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(“registry”);
最終獲得的對象爲ProtocolFilterWrapper(ProtocolListenerWrapper(RegistryProtocol))
那麼把前文連接起來,猜想:
1. ExtensionFactory是用來生產Extension的擴展類
2. ExtensionLoader是用來生產實現類的擴展類
3. getAdaptiveExtension()是獲取該Extension的默認實現類
猜想1.
由ExtensionFactory可以找到com.alibaba.dubbo.common.extension.ExtensionFactory
,裏面有三種實現spi、spring、adaptive.那麼它的調用模式會根據此時獲取的extension的類型進行選擇性的調用三種實現類的方法。
例如SpiExtensionFactory:
public class SpiExtensionFactory implements ExtensionFactory {
public SpiExtensionFactory() {
}
public <T> T getExtension(Class<T> type, String name) {
//如果該接口標註了@SPI
if(type.isInterface() && type.isAnnotationPresent(SPI.class)) {
//調用ExtensionLoader.getExtensionLoader(type).getAdaptiveExtension()
//獲取默認實現類
ExtensionLoader loader = ExtensionLoader.getExtensionLoader(type);
if(loader.getSupportedExtensions().size() > 0) {
return loader.getAdaptiveExtension();
}
}
return null;
}
}
猜想驗證,且應該是ExtensionFactory是用來生產或獲取Extension的擴展類,例如從spring容器獲取(實例化工作是由spring來完成的)
猜想2.
通過追蹤調用鏈找到createExtension(String name),真正進行了實例化
猜想驗證
猜想3.
通過追蹤調用鏈找到實例化對象爲Protocol$Adaptive(以Protocol爲例)
發現在方法調用過程中有這樣的一句話:
//SPI中配置項爲"dubbo",所以這裏編譯出來的默認值爲dubbo
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
且該方法上標註了@Adaptive的註解
可見,@SPI中的註解表示該接口的默認實現類而在方法上標註@Adaptive註解,則是在該方法上增加可選項,允許通過傳入不同的extName(這個例子是通過getProtocol的方式獲得此時應該適應的對象)來調用自適應對象的方法。
通俗的理解就是,
當接口類上標註了@SPI註解,說明了該接口類的默認實現類
當接口類上標註了@SPI註解,且方法上標註了@Adaptive,則說明了該接口類的該方法需要根據情況調用不同的實現類
當接口類上標註了@Adaptive,則說明是根據需要直接實例化某實現類
詳情可以查閱@SPI和@Adaptive註解說明。
雖然猜想3不能完成驗證,但至少通過跟蹤分析了SPI的調用鏈路讓我們有比較充分的理由這樣推測。