Dubbo SPI 源碼學習 & admin安裝(二)

筆記簡述
本學習筆記主要是介紹了SPI的使用以及原理,dubbo是如何實現自身的SPI,dubbo如何使用的可以看Dubbo 簡要介紹和使用 學習(一)
更多內容可看[目錄]Dubbo 源碼學習

目錄

Dubbo SPI 源碼學習 & admin安裝(二)
1、SPI
1.1、Java SPI DEMO
1.2、Java SPI 源碼實現
2、Dubbo SPI 配置
3、Dubbo SPI 使用 & 源碼學習
3.1、 Protocol 獲取
3.2、SPI配置文件解析
4、dubbo-admin 安裝使用

1、SPI

在dubbo中包含了很多組件,各種組件又有不同的協議使得存在多種實現,而且在開發中都是推薦針對接口編程,那就存在一個問題了,如何選擇合適的實現類呢?解決方案就是SPI

SPI的全名為Service Provider Interface,提供類似于插拔式的實現類選擇能力。在java中使用的類是java.util.ServiceLoader,然后在META-INF/services/創建的具體文件中寫上具體的實現類的類名稱,就可以實現具體的類,在早期的JDBC中,必須得通過Class.forName("xxx")這種硬編碼的方式去生成對應類的實例,但是現在可以直接通過SPI達到同樣的目的

1.1、Java SPI DEMO

public interface Search {
    void print();
}
public class FileSearch implements Search {

    @Override
    public void print() {
        System.out.println("==== A ====");
    }
}
public class SpiTest {

    public static void main(String[] args){
        ServiceLoader<Search> serviceLoader = ServiceLoader.load(Search.class);
        Iterator<Search> it = serviceLoader.iterator();
        while (it.hasNext()){
            Search printImpl = it.next();
            printImpl.print();
        }
    }
}

spi.Search

spi.FileSearch
spi.WebSearch
image

如上圖,需要在資源文件的根目錄創建一個META-INF.services的文件夾,新建一個Search接口完整路徑的文件,本例子是spi.Search,里面填入實現類的類全程。如下圖,確實調用了兩個具體的實例,迭代分別執行。

image

1.2、Java SPI 源碼實現

如下圖,首先獲取到fullName數據,然后調用getResource獲取該文件內的資源


image
    private Iterator<String> parse(Class<?> service, URL u)
        throws ServiceConfigurationError
    {
        InputStream in = null;
        BufferedReader r = null;
        ArrayList<String> names = new ArrayList<>();
        try {
            in = u.openStream();
            r = new BufferedReader(new InputStreamReader(in, "utf-8"));
            int lc = 1;
            while ((lc = parseLine(service, u, r, lc, names)) >= 0);
        } catch (IOException x) {
            fail(service, "Error reading configuration file", x);
        } finally {
            try {
                if (r != null) r.close();
                if (in != null) in.close();
            } catch (IOException y) {
                fail(service, "Error closing configuration file", y);
            }
        }
        return names.iterator();
    }

然后解析文件內的內容,存入到一個ArrayList中,并返回其迭代器(后面肯定還差一步就是實例化)

image

很明顯了,在獲取到類信息,直接調用newInstance方法完成實例化操作

同時根據newInstance也可以知道對外提供的spi的實現類不能有自定義的構造函數

2、Dubbo SPI 配置

dubbo的spi和java自帶的spi稍有區別,如上述的demo中,是在文件中寫入什么實現類,就會去實現,如果需要獲取其中的一個,則需要循環迭代獲取處理,而在dubbo中則采用了類似kv對的樣式,在具體使用的時候則通過相關想法即可獲取,而且獲取的文件路徑也不一致

ExtensionLoader 類文件

private static final String SERVICES_DIRECTORY = "META-INF/services/";

private static final String DUBBO_DIRECTORY = "META-INF/dubbo/";
    
private static final String DUBBO_INTERNAL_DIRECTORY = DUBBO_DIRECTORY + "internal/";

如上述代碼片段可知,dubbo是支持從META-INF/dubbo/,META-INF/dubbo/internal/以及META-INF/services/三個文件夾的路徑去獲取spi配置

image

例如com.alibaba.dubbo.rpc.Protocol 文件內容

registry=com.alibaba.dubbo.registry.integration.RegistryProtocol
filter=com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper
listener=com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper
mock=com.alibaba.dubbo.rpc.support.MockProtocol
injvm=com.alibaba.dubbo.rpc.protocol.injvm.InjvmProtocol
dubbo=com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
rmi=com.alibaba.dubbo.rpc.protocol.rmi.RmiProtocol
hessian=com.alibaba.dubbo.rpc.protocol.hessian.HessianProtocol
com.alibaba.dubbo.rpc.protocol.http.HttpProtocol
com.alibaba.dubbo.rpc.protocol.webservice.WebServiceProtocol
thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftProtocol
memcached=memcom.alibaba.dubbo.rpc.protocol.memcached.MemcachedProtocol
redis=com.alibaba.dubbo.rpc.protocol.redis.RedisProtocol

不過觀察上述文件會發現,HttpProtocol是沒有對應的k值,那就是說無法通過kv對獲取到其協議實現類

后面通過源碼可以發現,如果沒有對應的name的時候,dubbo會通過findAnnotationName方法獲取一個可用的name

3、Dubbo SPI 使用 & 源碼學習

通過獲取協議的代碼來分析下具體的操作過程

3.1、 Protocol 獲取

Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

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);
    // 從map中獲取該類型的ExtensionLoader數據
    if (loader == null) {
        EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
        // 如果沒有則,創建一個新的ExtensionLoader對象,并且以該類型存儲
        loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
        // 再從map中獲取
        // 這里這樣做的原因就是為了防止并發的問題,而且map本是也是個ConcurrentHashMap
    }
    return loader;
}
private ExtensionLoader(Class<?> type) {
    this.type = type;
    objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
// 傳入的type是Protocol.class,所以需要獲取ExtensionFactory.class最合適的實現類
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);
        }
    }

    return (T) instance;
}
private T createAdaptiveExtension() {
    try {
        return injectExtension((T) getAdaptiveExtensionClass().newInstance());
        // (T) getAdaptiveExtensionClass().newInstance() 創建一個具體的實例對象
        // getAdaptiveExtensionClass() 生成相關的class
        // injectExtension 往該對象中注入數據
    } catch (Exception e) {
        throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
    }
}
private Class<?> getAdaptiveExtensionClass() {
    getExtensionClasses();
    // 通過加載SPI配置,獲取到需要的所有的實現類存儲到map中
    // 通過可能會去修改cachedAdaptiveClass數據,具體原因在spi配置文件解析中分析
    if (cachedAdaptiveClass != null) {
        return cachedAdaptiveClass;
    }
    return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
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);
    // 編譯,生成相應的類
}

如下代碼Protocol$Adpative 整個的類就是通過createAdaptiveExtensionClassCode()方法生成的一個大字符串

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 {  
        // 暴露遠程服務,傳入的參數是invoke對象
        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() );  
        // 如果沒有具體協議,則使用dubbo協議
  
        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 {  
        // 引用遠程對象,生成相對應的遠程invoke對象
        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的方法Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension()返回了一個代碼拼接而成然后編譯操作的實現類Protocol$Adpative

可是得到具體的實現呢?在com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName)這個代碼中,當然這個是有在具體的暴露服務或者引用遠程服務才被調用執行的。

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);
    }
    // 無論是否真有數據,在cachedInstances存儲的是一個具體的Holder對象
    Object instance = holder.get();
    if (instance == null) {
        synchronized (holder) {
            instance = holder.get();
            if (instance == null) {
                instance = createExtension(name);
                // 創建對象
                holder.set(instance);
            }
        }
    }
    return (T) instance;
}
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());
            // clazz.newInstance 才是真正創建對象的操作
            instance = (T) EXTENSION_INSTANCES.get(clazz);
        }
        injectExtension(instance);
        // 往實例中反射注入參數
        Set<Class<?>> wrapperClasses = cachedWrapperClasses;
        if (wrapperClasses != null && wrapperClasses.size() > 0) {
            for (Class<?> wrapperClass : wrapperClasses) {
                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);
    }
}

到這一步就可以認為是dubbo的spi加載整個的過程完成了,整個鏈路有些長,需要好好的梳理一下

3.2、SPI配置文件解析

上文3.1說到getExtensionClasses完成對spi文件的解析

private Map<String, Class<?>> loadExtensionClasses() {
    final SPI defaultAnnotation = type.getAnnotation(SPI.class);
    // 查看該類是否存在SPI注解信息
    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];
            // 設置默認的名稱,如果注解的值經過切割,發現超過1個的數據,則同樣會認為錯誤
        }
    }
    
    Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
    loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
    // 加載文件
    loadFile(extensionClasses, DUBBO_DIRECTORY);
    loadFile(extensionClasses, SERVICES_DIRECTORY);
    return extensionClasses;
}
    
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
    String fileName = dir + type.getName();
    // type.getName就是類名稱,和java的類似
    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) {
                            final int ci = line.indexOf('#');
                            if (ci >= 0) line = line.substring(0, ci);
                            line = line.trim();
                            if (line.length() > 0) {
                                try {
                                    String name = null;
                                    int i = line.indexOf('=');
                                    // 對k=v這樣的格式進行分割操作,分別獲取
                                    if (i > 0) {
                                        name = line.substring(0, i).trim();
                                        line = line.substring(i + 1).trim();
                                    }
                                    if (line.length() > 0) {
                                        Class<?> clazz = Class.forName(line, true, classLoader);
                                        if (! type.isAssignableFrom(clazz)) {
                                            throw new IllegalStateException("Error when load extension class(interface: " +
                                                    type + ", class line: " + clazz.getName() + "), class " 
                                                    + clazz.getName() + "is not subtype of interface.");
                                        }
                                        if (clazz.isAnnotationPresent(Adaptive.class)) {
                                            // 如果獲取的類包含了Adaptive注解
                                            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 {  // 不包含Adaptive注解信息
                                            try {
                                                clazz.getConstructor(type);
                                                // 查看構造函數是否包含了type的類型參數
                                                // 如果不存在,則拋出NoSuchMethodException異常
                                                Set<Class<?>> wrappers = cachedWrapperClasses;
                                                if (wrappers == null) {
                                                    cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
                                                    wrappers = cachedWrapperClasses;
                                                }
                                                wrappers.add(clazz);
                                                // 往wrappers中添加該類
                                            } catch (NoSuchMethodException e) {
                                                clazz.getConstructor();
                                                if (name == null || name.length() == 0) {
                                                   // 沒用名字的那種,也就是不存在k=v這種樣式
                                                   // 例如上面的HttpProtocol
                                                    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) {
                                                    Activate activate = clazz.getAnnotation(Activate.class);
                                                    if (activate != null) {
                                                        // 如果類存在Activate的注解信息
                                                        cachedActivates.put(names[0], activate);
                                                    }
                                                    for (String n : names) {
                                                        if (! cachedNames.containsKey(clazz)) {
                                                            cachedNames.put(clazz, n);
                                                        }
                                                        Class<?> c = extensionClasses.get(n);
                                                        if (c == null) {
                                                            extensionClasses.put(n, clazz);
                                                            // 往容器中填充該鍵值對信息,k和v
                                                        } else if (c != clazz) {
                                                             // 存在多個同名擴展類,則拋出異常信息
                                                            throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } catch (Throwable t) {
                                    IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t);
                                    exceptions.put(line, e);
                                }
                            }
                        } // 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);
    }
}

這樣完成了對spi配置文件的整個的掃描過程了

4、dubbo-admin 安裝使用

在上一節中利用dubbo-admin查看了服務提供方和服務調用方,現在就來簡要的介紹下如何在本地跑起來admin,先從github拉取代碼incubator-dubbo-ops到本地,在maven環境下,依賴maven-tomcat插件啟動,并沒有打包成war包丟到Tomcat下啟動

添加注冊組信息

dubbo-admin.xml 文件添加注冊組信息

<dubbo:registry client="curator" address="${dubbo.registry.address}" group="${dubbo.register.group}" check="false" file="false"/>

對應的配置文件信息,添加組的具體內容

dubbo.properties

dubbo.registry.address=zookeeper://127.0.0.1:2182
dubbo.register.group=dubbo-demo
dubbo.admin.root.password=root   // root用戶的密碼是root
dubbo.admin.guest.password=guest   // guest用戶的密碼是guest

添加Tomcat插件運行

在pom.xml文件內添加如下代碼

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <uriEncoding>UTF-8</uriEncoding>
                <port>8112</port>
                <path>/</path>
            </configuration>
        </plugin>
    </plugins>
</build>

接下來就可以使用mvn tomcat7:run -Dport=8112或者IDEA 的maven工具直接啟動

image

在瀏覽器輸入127.0.0.1:8112,輸入賬戶名和秘密(分別都是root),就進入到admin后臺頁面

image

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Dubbo采用微內核+插件體系,使得設計優雅,擴展性強。那所謂的微內核+插件體系是如何實現的呢!大家是否熟悉spi...
    carl_zhao閱讀 957評論 1 3
  • 前面我們了解過了Java的SPI擴展機制,對于Java擴展機制的原理以及優缺點也有了大概的了解,這里繼續深入一下D...
    加大裝益達閱讀 5,091評論 2 20
  • 0 前言 站在一個框架作者的角度來說,定義一個接口,自己默認給出幾個接口的實現類,同時 允許框架的使用者也能夠自定...
    七寸知架構閱讀 16,295評論 3 67
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,908評論 18 139
  • 我的母親,是位典型的家庭主婦,小時候因為要干農活和帶弟弟妹妹,沒有像樣的上過一天學。但是母親還是識字的,她利...
    邵楊楊閱讀 333評論 1 7