Dubbo源碼閱讀筆記3

来源:https://www.cnblogs.com/amwyyyy/archive/2018/01/25/8353523.html
-Advertisement-
Play Games

擴展點載入(ExtensionLoader) 每一種類型的擴展點都有一個ExtensionLoader實例 1. 變數說明 2. 初始化 先從全局緩存裡面取,如果取不到則新建 ExtensionLoader構建方法,保存擴展點介面類型和對象工廠 擴展點對象工廠也是從通過ExtensionLoader ...


### 擴展點載入(ExtensionLoader)

每一種類型的擴展點都有一個ExtensionLoader實例

  1. 變數說明

    public class ExtensionLoader<T> {
    // dubbo服務掃描目錄
    private static final String SERVICES_DIRECTORY = "META-INF/services/";
    // dubbo擴展點配置掃描目錄(自定義擴展時使用此目錄)
    private static final String DUBBO_DIRECTORY = "META-INF/dubbo/";
    // dubbo內部擴展點配置掃描目錄
    private static final String DUBBO_INTERNAL_DIRECTORY = DUBBO_DIRECTORY + "internal/";
    
    private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");
    
    // 緩存ExtensionLoader
    private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>();
    // 緩存擴展點實例
    private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<Class<?>, Object>();
    
    // 前面是常量,以下是變數
    // ==============================
    
    // 當前擴展點的介面類型
    private final Class<?> type;
    
    // 對象工廠
    private final ExtensionFactory objectFactory;
    
    private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<Class<?>, String>();
    
    // 該擴展點類型所有配置的實現類類型
    private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<Map<String, Class<?>>>();
    
    // 配置中自適應擴展的註解信息
    private final Map<String, Activate> cachedActivates = new ConcurrentHashMap<String, Activate>();
    
    // 擴展點實例
    private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<String, Holder<Object>>();
    
    // 自適應擴展點實例
    private final Holder<Object> cachedAdaptiveInstance = new Holder<Object>();
    
    // 自適應擴展點類型
    private volatile Class<?> cachedAdaptiveClass = null;
    
    // 預設擴展點的名
    private String cachedDefaultName;
    
    // 包裝類類型
    private Set<Class<?>> cachedWrapperClasses;
    
    private volatile Throwable createAdaptiveInstanceError;
    
    private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<String, IllegalStateException>();
    
    // ...
    }
  2. 初始化

先從全局緩存裡面取,如果取不到則新建

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);
    if (loader == null) {
        EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
        loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
    }
    return loader;
}

ExtensionLoader構建方法,保存擴展點介面類型和對象工廠
擴展點對象工廠也是從通過ExtensionLoader載入出來的

private ExtensionLoader(Class<?> type) {
    this.type = type;
    objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
  1. 獲取擴展點實例

先從緩存中取,如果沒有則開始創建
Holder對象主要是上同步鎖的時候用,鎖在Holder級別,保證之後get和set方法原子性

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是在同步塊中調用的,所以不需要加synchroneized,是線程安全的

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) {
                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);
    }
}

// 獲取所有擴展點類型的map,如果緩存中沒有就從配置文件中取出
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;
}
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())) {
                    Class<?> pt = method.getParameterTypes()[0];
                    try {
                        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) {
                            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;
}

預設的對象工廠實現是AdaptiveExtensionFactory,其實就是SpringExtensionFactory和SpiExtensionFactory兩個一起用。
主要看SpiExtensionFactory實現
可以看出這裡進入了遞歸,直到相關擴展點全部載入完成

public <T> T getExtension(Class<T> type, String name) {
    if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
        ExtensionLoader<T> loader = ExtensionLoader.getExtensionLoader(type);
        if (loader.getSupportedExtensions().size() > 0) {
            return loader.getAdaptiveExtension();
        }
    }
    return null;
}

前面的代碼是返回普通擴展點,接下來的是返回自適應擴展點,AdaptiveExtension
自適應擴展點不同的地方在於,不是直接返回擴展點實現,而是通過位元組碼技術生成一個代理類,
代理類會根據調用時的參數不同,再去選擇不同的擴展點實現。也就是調用了獲取擴展點的方法getExtension(name)

// 和普通擴展點基本一致
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;
}

// 這裡類型不是從getExtensionClasses中取而是getAdaptiveExtensionClass
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);
    }
}

private Class<?> getAdaptiveExtensionClass() {
    getExtensionClasses();
    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);
}

createAdaptiveExtensionClassCode代碼太長就不貼出來了
這是其中一個擴展點生成的源代碼,可以看出代碼里根據url中的參數選擇合適的擴展點實現
這些用反射用動態代理也是可以做的,不過效率肯定沒位元組碼好,這個可以學習下。

package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
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.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);
    }
}

為了方便理解下麵上個小例子

新建一個maven項目,結構如下:

|--pom.xml
|--src
    |--main
        |--java
            |--com
                |--serviceloader
                    |--service
                        |--Book.java
                        |--Car.java
                        |--English.java
                        |--Honda.java
                        |--Human.java
                        |--Man.java
                    |--ServiceLoader.java
                    |--SPI.java
        |--resources
            |--config.properties

SPI註解,用來指定實現者

// SPI.java
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface SPI {
    String value() default "";
}

建3個介面,並加上註解,設置預設實現者

@SPI("english")
public interface Book {
    String read();
}

@SPI("honda")
public interface Car {
    void driver(String name);
}

// 也可以是woman
@SPI("man")
public interface Human {
    String sayHello();
}

以及實現者

public class Man implements Human {
    private Car car;
    private Book book;

    @Override
    public String sayHello() {
        return "hello man";
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }
}

public class Woman implements Human {
    @Override
    public String sayHello() {
        return "hello man";
    }
}

public class Honda implements Car {
    private Book book;

    @Override
    public void driver(String name) {
        System.out.println("i am " + name);
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }
}

public class English implements Book {
    @Override
    public String read() {
        return "hello my name is denis";
    }
}

配置文件,用來配置實現者的類型

man=com.serviceloader.service.Man
woman=com.serviceloader.service.Woman
english=com.serviceloader.service.English
honda=com.serviceloader.service.Honda

最後是服務載入器

public class ServiceLoader {
    private static ConcurrentMap<Class<?>, Object> SERVICE_INSTANCES = new ConcurrentHashMap<>();
    private static ConcurrentMap<String, Class<?>> SERVICE_CLASS;

    @SuppressWarnings("unchecked")
    public static <T> T get(Class<T> clazz) {
        if (SERVICE_CLASS == null) {
            SERVICE_CLASS = getServiceClass();
        }

        SPI spi = clazz.getAnnotation(SPI.class);
        if (spi == null) {
            throw new RuntimeException("不是SPI介面");
        }

        Class<?> targetClass = SERVICE_CLASS.get(spi.value());  // 這裡可以根據其它配置更換實現者
        if (targetClass == null) {
            throw new RuntimeException("沒有配置實現類型");
        }

        try {
            T instance = (T) SERVICE_INSTANCES.get(clazz);
            if (instance == null) {
                SERVICE_INSTANCES.putIfAbsent(clazz, targetClass.newInstance());
                instance = (T) SERVICE_INSTANCES.get(clazz);
            }

            injectExtension(instance);

            return instance;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 註入屬性
     *
     * @param instance
     * @param <T>
     */
    private static <T> void injectExtension(T instance) {
        Method[] methods = instance.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().startsWith("set") && method.getName().length() > 3
                    && method.getParameterTypes().length == 1
                    && Modifier.isPublic(method.getModifiers())) {
                try {
                    Class<?> pt = method.getParameterTypes()[0];
                    Object object = get(pt);  // 遞歸

                    if (object != null) {
                        method.invoke(instance, object);
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 從配置文件中取出實現者名稱與類型對應map
     *
     * @return
     */
    private static ConcurrentMap<String,Class<?>> getServiceClass() {
        try {
            if (SERVICE_CLASS == null) {
                synchronized (ServiceLoader.class) {
                    if (SERVICE_CLASS == null) {
                        SERVICE_CLASS = new ConcurrentHashMap<>();

                        InputStream is = ServiceLoader.class.getClassLoader().getResourceAsStream("config.properties");
                        Properties p = new Properties();
                        p.load(is);

                        Set<String> keys = p.stringPropertyNames();
                        for (String key : keys) {
                            Class<?> clazz = Class.forName(String.valueOf(p.get(key)));
                            SERVICE_CLASS.putIfAbsent(key, clazz);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SERVICE_CLASS;
    }

    public static void main(String[] args) {
        Human human = ServiceLoader.get(Human.class);
        System.out.println("class : " + human.getClass().getName());
        System.out.println(human.sayHello());

        Car car = ServiceLoader.get(Car.class);
        System.out.println("class : " + car.getClass().getName());
        car.driver("大卡車");

        Book book = ServiceLoader.get(Book.class);
        System.out.println("class : " + book.getClass().getName());
        System.out.println(book.read());
    }
}

運行後輸出:

class : com.serviceloader.service.Man
hello man
class : com.serviceloader.service.Honda
i am 大卡車
class : com.serviceloader.service.English
hello my name is denis

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Markdown 語法快速入門 [TOC](博客園Markdown引擎暫不支持) 標題 第一級標題 第二級標題 第六級標題 強調 斜體字 : _斜體字_: 加粗 : __斜體字__: 列表 無序列表: 有序列表: 任務列表: [ ]未完成任務 [x] 已完成任務 插入鏈接及圖片 插入鏈接: Eg. ...
  • QT5 TCP網路通訊 伺服器與客戶端建立連接listen() - connectToHost(); 觸發newPendingConnect信號 實時數據通訊write(); read(); 觸發readyRead信號 通訊主要使用的類: QTcpServer Class QTcpServer類提供 ...
  • 問題: 給定一個n*n的棋盤,棋盤中有一些位置不能放皇後。現在要向棋盤中放入n個黑皇後和n個白皇後,使任意的兩個黑皇後都不在同一行、同一列或同一條對角線上,任意的 兩個白皇後都不在同一行、同一列或同一條對角線上。問總共有多少種放法?n小於等於8。 輸入格式 輸入的第一行為一個整數n,表示棋盤的大小。 ...
  • 多註冊中心,一般用不到,但是某些情況下的確能解決不少問題,可以將某些dubbo服務註冊到2套dubbo系統中,實現服務在2套系統間的共用. 網上的配置說明很多,但包括dubbo官方說明文檔都是以xml文件配置方式舉例. 如想採用javaconfig的配置方式,則只需要對provider中的配置做適當 ...
  • session淺析 1.對於會話技術的理解 web會話技術包含Session和Cookie,會話技術是瀏覽器端與伺服器端的交互技術,拿cookie技術來說,客戶端在請求伺服器端的時候,如果有業務需要,伺服器會設置響應頭的key值與value值,在響應的時候帶給瀏覽器端,然後瀏覽器端在符合path條件 ...
  • 靜態頁面分為兩種,一種為jsp,另一種為html。 先看jsp的 在登陸的form表單中添加添加type為checkbox的input標簽 為該checkbox增加點擊事件 在後臺登錄方法中根據remember的值判斷是否設置Cookie 在頁面載入完後,獲取Cookie,並存入pageContex ...
  • import re # 正則表達式,用於提取數據 import requests # 下載網頁源代碼 ''' 安裝requests模塊:pip install requests 參考文檔:https://www.cnblogs.com/jamespan23/p/5526311.html ''' fo... ...
  • Logback介紹 Logback是由log4j創始人設計的又一個開源日誌組件。logback當前分成三個模塊:logback core,logback classic和logback access。logback core是其它兩個模塊的基礎模塊。logback classic是log4j的一個 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...