Dubbo SPI源碼解析①

​ SPI英文全稱爲Service Provider Interface。它的作用就是將接口實現類的全限定名寫在指定目錄的配置文件中,使框架讀取配置文件,從而加載實現類。這樣我們就可以動態的爲接口替換實現類,使得框架拓展性更高。Java其實也有原生的SPI機制,但是Dubbo並未使用它。學習Dubbo源碼的前提就是得弄懂Dubbo SPI機制。

0.Java SPI示例

public interface Hello{
    void sayHello();
}
public class testA implements Hello{
    @Override
    public void sayHello(){
        System.out.println("Hello,I am A");
    }
}

public class testB implements Hello{
    @Override
    public void sayHello(){
        System.out.println("Hello,I am B");
    }
}

​ 寫好實現類和接口後,我們需要在META-INF/services目錄下新建一個文件,名稱爲接口Hello的全限定名。然後在文件裏面寫上所有實現類的全限定名,例如:

com.yelow.spi.testA 
com.yelow.spi.testB

​ 測試

public class JavaSPITest{
    @Test
    public void sayHello()  throws Exception{
        ServiceLoader<Hello> serviceLoader = ServiceLoader.load(Hello.class);
        serviceLoader.forEach(Hello::sayHello);
        //分別輸出:
        //Hello,I am A
        //Hello,I am B
    }
}

1.Dubbo SPI示例

​ Dubbo SPI的使用上,和Java SPI類似的。先定義接口和實現類,接口前加上@SPI註解,代表一個拓展點。再創建一個配置文件。但是這個文件的路徑應該在META-INF/dubbo/路徑下。配置文件內容應該變成鍵值對形式,例如:

testA = com.yelow.spi.testA 
testB = com.yelow.spi.testB

​ 最後測試方法爲:

public class JavaSPITest{
    @Test
    public void sayHello()  throws Exception{
        ExtensionLoader<Hello> loader=ExtensionLoader.getExtensionLoader(Hello.class);
        //按需加載,參數爲配置文件中的key值
        Hello testA=loader.getExtension("testA");
        testA.sayHello();
        //輸出Hello,I am A
    }
}

2.Dubbo SPI源碼分析

​ 上面簡單演示了Dubbo的使用方法。先通過ExtensionLoader.getExtensionLoader獲取ExtensionLoader對象。在通過這個對象的getExtension方法獲取實現類對象。先看一下getExtensionLoader方法:

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對象
    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;
}

​ getExtensionLoader方法比較簡單,我們接着看一下getExtension:

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中
                holder.set(instance);
            }
        }
    }
    return (T) instance;
}

​ 同樣的,也是先檢查緩存,沒有緩存再新建。下面我們看一下是怎麼新建實例對象的,進入到createExtension方法:

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);
        }
        //向實例對象中注入依賴
        injectExtension(instance);
        Set<Class<?>> wrapperClasses = cachedWrapperClasses;
        if (wrapperClasses != null && wrapperClasses.size() > 0) {
            for (Class<?> wrapperClass : wrapperClasses) {
                //將當前實例對象作爲參數傳給Wrapper的構造方法,並通過反射創建Wrapper對象
                //再向wrapper實例對象中注入依賴,最後把wrapper賦值給instance
                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);
    }
}

​ 上面的方法中,給instance賦值的那行代碼稍微有點複雜,其實最終目的只是把實現類對象包裹在Wrapper對象中。從上面的註釋看,createExtension方法的目的有四個。重點關注getExtensionClasses和injectExtension方法:

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方法:

private Map<String, Class<?>> loadExtensionClasses() {
    //獲取SPI註解
    final SPI defaultAnnotation = type.getAnnotation(SPI.class);
    if (defaultAnnotation != null) {
        String value = defaultAnnotation.value();
        if (value != null && (value = value.trim()).length() > 0) {
            //對SPI註解的值進行拆分
            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;
}

​ 我們看一下loadFile方法指定的目錄常量分別是啥:

​ 可以看到,前面示例說到的目錄就是在這規定的。而META-INF/services/是爲了兼容Java SPI,internal/是Dubbo內部自己的拓展類配置文件。最後我們分析一下loadFile方法:

private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
    //文件夾路徑+接口全限定名=配置文件具體路徑
    String fileName = dir + type.getName();
    try {
        Enumeration<java.net.URL> urls;
        ClassLoader classLoader = findClassLoader();
        //根據文件名加載所有同名文件
        if (classLoader != null) {
            urls = classLoader.getResources(fileName);
        } else {
            urls = ClassLoader.getSystemResources(fileName);
        }
        //獲取到文件後進行遍歷讀取配置文件
        if (urls != null) {
            while (urls.hasMoreElements()) {
                java.net.URL url = urls.nextElement();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
                    try {
                        String line = null;
                        //按行讀取
                        while ((line = reader.readLine()) != null) {
                            //解析配置文件
                            //通過反射加載實現類
                            //操作緩存
                            //略。。。,最好自己debug調試一下,最清楚
                        } // end of while read lines
                    } finally {
                        reader.close();
                    }
                } catch (Throwable t) {
                    logger.error("Exception when load extension class(interface: " +
                            type + ", class file: " + url + ") in " + url, t);
                }
            } // end of while urls
        }
    } catch (Throwable t) {
        logger.error("Exception when load extension class(interface: " +
                type + ", description file: " + fileName + ").", t);
    }
}

​ 獲取實現類的源碼分析的差不多了,現在回到createExtension方法,接着看看injectExtension,也就是Dubbo的依賴注入功能。Dubbo IOC是通過setter方法注入依賴。它會通過反射獲取實例的方法列表,再遍歷方法是否具備setter方法的特徵,若有就通過反射調用這個setter方法將依賴設置到目標對象中。代碼分析如下:

private T injectExtension(T instance) {
    try {
        if (objectFactory != null) {
            //遍歷方法
            for (Method method : instance.getClass().getMethods()) {
                //判斷方法是否以set開頭,且只有一個參數,且方法是public
                if (method.getName().startsWith("set")
                        && method.getParameterTypes().length == 1
                        && Modifier.isPublic(method.getModifiers())) {
                            //獲取setter方法參數類型
                    Class<?> pt = method.getParameterTypes()[0];
                    try {
                        //獲取熟悉名,比如setName,其對應的屬性應該是name
                        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) {
                            //通過反射調用setter方法完成依賴注入
                            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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章