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

weixin_34146805發表於2018-04-24

筆記簡述
本學習筆記主要是介紹了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
2064197-706af05b5bc8a9a2.jpg
image

如上圖,需要在資原始檔的根目錄建立一個META-INF.services的資料夾,新建一個Search介面完整路徑的檔案,本例子是spi.Search,裡面填入實現類的類全程。如下圖,確實呼叫了兩個具體的例項,迭代分別執行。

2064197-f08e6c5faf441967.jpg
image

1.2、Java SPI 原始碼實現

如下圖,首先獲取到fullName資料,然後呼叫getResource獲取該檔案內的資源


2064197-4ca7d09c44e426f8.jpg
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中,並返回其迭代器(後面肯定還差一步就是例項化)

2064197-5bec467a0de5524c.jpg
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配置

2064197-8840e3a34cb8c95a.jpg
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工具直接啟動

2064197-d0272a7d76b9ecd8.jpg
image

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

2064197-75c8294e5aa972cb.jpg
image

相關文章