本身用Dubbo也有幾年時間,一直沒有讀過Dubbo的源碼,如今來讀一讀Dubbo的源碼,分析一下Dubbo的幾個核心,並寫一個Dubbo的源碼專題來記錄一下學習過程,供你們參考,寫的很差的地方,歡迎拍磚
專題分爲如下幾個部分:java
PS:讀源碼前先掌握如下基礎spring
PS:讀源碼前的建議設計模式
之因此選擇先從Dubbo的擴展點機制入手,由於Dubbo的總體架構設計上,都是經過擴展點去實現,先了解清楚這塊內容,才能讀懂代碼。緩存
Dubbo的擴展點(Extension)在JDK的SPI思想的基礎上作了一些改進:bash
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
複製代碼
getExtensionLoader方法中傳入的了一個Protocol,咱們看下Protocol長啥樣多線程
@SPI("dubbo")
public interface Protocol {
//獲取缺省端口,當用戶沒有配置端口時使用。
int getDefaultPort();
// 暴露遠程服務:<br>
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
//引用遠程服務:<br>
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
//釋放協議:<br>
void destroy();
複製代碼
這是一個協議接口,在類上有@SPI註解,有個默認值dubbo,在方法上有@Adaptive註解,這兩個註解是什麼做用呢?咱們繼續往下看getExtensionLoader方法:架構
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
·····
//先從緩存中取值,爲null,則去new一個ExtensionLoader
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;
}
複製代碼
繼續進入new ExtensionLoader(type)方法:app
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
複製代碼
給type變量賦值,objectFactory賦值,此時傳入的type是Protcol,繼續執行ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension()方法,這裏咱們分爲兩個步驟:
步驟一:ExtensionLoader.getExtensionLoader(ExtensionFactory.class),此時type爲ExtensionFactory.class,這段代碼咱們獲得一個ExtensionLoader實例,這個ExtensionLoader實例中,objetFactory爲null, 步驟二:getAdaptiveExtension()方法,爲cachedAdaptiveInstance賦值,咱們來看這個方法:框架
public T getAdaptiveExtension() {
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);
}
}
複製代碼
雙重檢查鎖判斷緩存,若是沒有則進入createAdaptiveExtension()方法,這個方法有兩部分,一個是injectExtension,一個是getAdaptiveExtensionClass().newInstance()jvm
private T createAdaptiveExtension() {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
}
}
複製代碼
先看getAdaptiveExtensionClass(),獲取一個適配器擴展點的類
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
複製代碼
這裏咱們進入getExtensionClasses()方法,雙重檢查鎖判斷,若是沒有,繼續
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
複製代碼
進入loadExtensionClasses()方法
// 此方法已經getExtensionClasses方法同步過。
private Map<String, Class<?>> loadExtensionClasses() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation != null) {
String value = defaultAnnotation.value();
if (value != null && (value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(value);
if (names.length > 1) {
throw new IllegalStateException("more than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if (names.length == 1) cachedDefaultName = names[0];
}
}
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
複製代碼
這裏有個type.getAnnotation(SPI.class),這個type就是剛剛再初始化ExtensionLoader的時候傳入的,咱們先看type=ExtensionFactory.class的狀況,ExtensionFactory接口類上有@SPI註解,可是value爲空,而後三次調用loadFile方法,分別對應Dubbo擴展點的三個配置文件路徑,在源碼中咱們能夠找到ExtensionFactory對應的文件,
經過loadFile方法,最終extensionClasses返回SpringExtensionFactory和SpiExtensionFactory 緩存到cachedClasses中,爲何只返回了2個類呢,AdaptiveExtensionFactory爲何沒有返回呢,由於在loadFile中AdaptiveExtensionFactory由於類上有@Adaptive註解,因此直接緩存到cachedAdaptiveClass中(此時,咱們要思考,@Adaptive註解放在類上和放在方法上有什麼區別),咱們看下loadFile中的關鍵代碼
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
····
// 1.判斷當前class類上面有沒有Adaptive註解,若是有,則直接賦值給cachedAdaptiveClass
if (clazz.isAnnotationPresent(Adaptive.class)) {
if (cachedAdaptiveClass == null) {
cachedAdaptiveClass = clazz;
} else if (!cachedAdaptiveClass.equals(clazz)) {
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getClass().getName()
+ ", " + clazz.getClass().getName());
}
} else {
//2.若是沒有類註解,那麼判斷該class中沒有參數是type的構造方法,若是有,則把calss放入cachedWrapperClasses中
try {
clazz.getConstructor(type);
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
//3.判斷是否有默認構造方法
clazz.getConstructor();
if (name == null || name.length() == 0) {
name = findAnnotationName(clazz);
if (name == null || name.length() == 0) {
if (clazz.getSimpleName().length() > type.getSimpleName().length()
&& clazz.getSimpleName().endsWith(type.getSimpleName())) {
name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase();
} else {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url);
}
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
//4.判斷class是否有@Activate註解,若是有,則放入cachedActivates
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
cachedActivates.put(names[0], activate);
}
for (String n : names) {
//5.緩存calss到cachedNames中
if (!cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
extensionClasses.put(n, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
}
}
}
}
}
}
}
複製代碼
至此,咱們已經拿到了extensionClasses,並緩存到了cachedClasses中,回到getAdaptiveExtensionClass()方法中
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
複製代碼
若是cachedAdaptiveClass不爲空,那麼就返回cachedAdaptiveClass,剛剛咱們在loadFile()方法中講過,@Adaptive註解在類上,那麼就會緩存到cachedAdaptiveClass中,這個時候cachedAdaptiveClass有值,爲AdaptiveExtensionFactory,因此這裏直接返回AdaptiveExtensionFactory,繼續返回createAdaptiveExtension()方法,剛剛咱們只是走完了createAdaptiveExtension()方法中的一個部分,還有injectExtension方法,這個方法是幹什麼的,在type=ExtensionFactory.class流程中,這個方法的做用沒有體現,先不看injectExtension,咱們放在後面的流程去看,而後繼續返回到getAdaptiveExtension方法中,把實例AdaptiveExtensionFactory緩存到cachedAdaptiveInstance中,繼續返回到ExtensionLoader方法中
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
複製代碼
這個時候,objectFactory已經有值了,就是AdaptiveExtensionFactory,繼續返回getExtensionLoader方法
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
····
//EXTENSION_LOADERS判斷是否有type,ConcurrentMap<Class<?>, ExtensionLoader<?>>
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;
}
複製代碼
咱們把返回的ExtensionLoader實例緩存到EXTENSION_LOADERS中,此時type=Protocol
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
複製代碼
至此,咱們已經執行完了ExtensionLoader.getExtensionLoader(Protocol.class),獲得了ExtensionLoader實例,繼續執行getAdaptiveExtension()方法,這個方法在上面已經分析過了,咱們再看下跟type=ExtensionFactory的時候有什麼區別,先看下com.alibaba.dubbo.rpc.Protocol文件中有哪些擴展點(這個文件在源碼中是分散的,能夠在Dubbo的jar包中找,jar包中是合併的)
這個時候再看下當前內存中的數據
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);
}
複製代碼
執行compiler.compile(code, classLoader),先看下AdaptiveCompiler類
@Adaptive
public class AdaptiveCompiler implements Compiler {
private static volatile String DEFAULT_COMPILER;
public static void setDefaultCompiler(String compiler) {
DEFAULT_COMPILER = compiler;
}
public Class<?> compile(String code, ClassLoader classLoader) {
Compiler compiler;
ExtensionLoader<Compiler> loader = ExtensionLoader.getExtensionLoader(Compiler.class);
String name = DEFAULT_COMPILER; // copy reference
if (name != null && name.length() > 0) {
compiler = loader.getExtension(name);
} else {
compiler = loader.getDefaultExtension();
}
return compiler.compile(code, classLoader);
}
}
複製代碼
這裏的DEFAULT_COMPILER值爲JavassistCompiler,執行loader.getExtension(name),這個方法這裏暫時不展開,結果是獲得JavassistCompiler實例,這裏是一個裝飾模式的設計,最終調用JavassistCompiler.compile()方法獲得Protocol$Adpative,
回到咱們最初的代碼的入口
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
複製代碼
這句代碼就最終的返回結果就是Protocol$Adpative,咱們把這個代理類拿出來看一下
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adpative 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.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();
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);
}
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);
}
}
複製代碼
這個時候若是執行Protocol$Adpative.export方法,咱們看下這個適配器代理類裏面的export()方法,經過url來獲取extName,因此Dubbo是基於URL來驅動的, 看到Protocol extension = (Protocol)ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(extName)這個方法,這個方法是否是又又又很熟悉,接下來咱們來分析getExtension(String name)方法,假設此時extName=dubbo
public T getExtension(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("Extension name == null");
if ("true".equals(name)) {
return getDefaultExtension();
}
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<Object>());
holder = cachedInstances.get(name);
}
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
instance = holder.get();
if (instance == null) {
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
複製代碼
進入createExtension()方法
private T createExtension(String name) {
//1.經過name獲取ExtensionClasses,此時爲DubboProtocol
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
//2.獲取DubboProtocol實例
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
//3.dubbo的IOC反轉控制,就是從spi和spring裏面提取對象賦值。
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
for (Class<?> wrapperClass : wrapperClasses) {
//4.若是是包裝類
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);
}
}
複製代碼
第三步injectExtension(instance),看一下代碼:
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
//1.拿到全部的方法
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) : "";
//從objectFactory中獲取所須要注入的實例
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;
}
複製代碼
這個方法就是Dubbo完成依賴注入的地方,到這裏關於Dubbo的擴展點機制的代碼就分析完成了。