Dubbo SPI 使用源码分析

本文通过分析 Dubbo 服务暴露过程中使用到的3个 SPI 加载的类 ExtensionFactoryProxyFactoryProtocol 来理解 SPI 的灵活加载逻辑。

以最简单的暴露服务到 jvm 为例,下面是位于 org.apache.dubbo.config.ServiceConfig 的关键源代码

// PROTOCOL 的动态类
private static final Protocol PROTOCOL = (Protocol)ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
// PROXY_FACTORY 的动态类
private static final ProxyFactory PROXY_FACTORY = (ProxyFactory)ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();

// 暴露服务到本地 jvm 中
private void exportLocal(URL url) {
    URL local = URLBuilder.from(url).setProtocol("injvm").setHost("127.0.0.1").setPort(0).build();
    Exporter exporter = PROTOCOL.export(PROXY_FACTORY.getInvoker(this.ref, this.interfaceClass, local));
    // ...
}

获取 AdaptiveClass

类中两个静态变量 PROXY_FACTORYPROTOCOL 使用了相同的方法初始化。

  1. 获取指定类的 ExtensionLoader 实例
  2. 通过 ExtensionLoader 实例调用 getAdaptiveExtension() 方法获取指定类的可扩展类。

获取指定 type 的 ExtensionLoader 方法如下:

public static  ExtensionLoader getExtensionLoader(Class type) {
    if (type == null) {
        throw new IllegalArgumentException("Extension type == null");
    } else if (!type.isInterface()) {
        throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
    } else if (!withExtensionAnnotation(type)) {
        throw new IllegalArgumentException("Extension type (" + type + ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
    } else {
        // 先查看是否已经生成过
        ExtensionLoader loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
        if (loader == null) {
            // 当 type=ProxyFactory 时,首次进入这里会初始化 ProxyFactory 类的 ExtensionLoader 实例
            // 并把实例都会缓存到静态变量中
            EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type));
            loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
        }

        return loader;
    }
}

关键是使用 ExtensionLoader 类的构造函数进行实例化的。

private ExtensionLoader(Class type) {
    this.type = type;
    // 当前 type=ProxyFactory, 它的 objectFactory 为 ExtensionFactory 类的动态类
    // 当 type=ExtensionFactory 时,它的 objectFactory 为 null
    this.objectFactory = type == ExtensionFactory.class ? null : (ExtensionFactory)getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension();
}

objectFactory 是用来在注入依赖的时候,获取依赖属性的对象工厂。它是 ExtensionFactory 类的 AdaptiveClass。
获取 ExtensionLoader的 AdaptiveClass,它的流程比较长,如下图:

ExtensionLoader 类加载.png

最终是在项目的 META-INF 指定文件夹中查找到 type 配置的所有实现类,获取到的 AdaptiveClass 有两种情况:

  1. Type 接口的实现类上有 @Adaptive 注解,则直接返回有此注解的类,如 type=ExtensionFactory 的实现类 AdaptiveExtensionFactory
  2. Type 接口的实现类上均无 @Adaptive 注解,但是实现类的方法上有此注解,则会在有注解的方法上动态生成实现类,如 type=ProxyFactory 接口均有 @Adaptive 方法,又 @SPI("javassist") 代表默认获取到的是 JavassistProxyFactory 类。
    (ProxyFactory)ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension() 获得的类如下:
package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.ExtensionLoader;
public class ProxyFactory$Adaptive implements org.apache.dubbo.rpc.ProxyFactory {

    public java.lang.Object getProxy(org.apache.dubbo.rpc.Invoker arg0) throws org.apache.dubbo.rpc.RpcException {
        // 检查是否参数异常
        if (arg0 == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument == null");
        if (arg0.getUrl() == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument getUrl() == null");

        org.apache.dubbo.common.URL url = arg0.getUrl();
        // 首先根据 url 中指定的 proxy 名称,为空的话默认使用 javassist 类名对应的 ProxyFactory 实现类
        String extName = url.getParameter("proxy", "javassist");
        if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
        org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
        return extension.getProxy(arg0);
    }

    public java.lang.Object getProxy(org.apache.dubbo.rpc.Invoker arg0, boolean arg1) throws org.apache.dubbo.rpc.RpcException {
        if (arg0 == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument == null");
        if (arg0.getUrl() == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument getUrl() == null");

        org.apache.dubbo.common.URL url = arg0.getUrl();
        String extName = url.getParameter("proxy", "javassist");
        if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
        org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
        return extension.getProxy(arg0, arg1);
    }

    public org.apache.dubbo.rpc.Invoker getInvoker(java.lang.Object arg0, java.lang.Class arg1, org.apache.dubbo.common.URL arg2) throws org.apache.dubbo.rpc.RpcException {
        if (arg2 == null) throw new IllegalArgumentException("url == null");

        org.apache.dubbo.common.URL url = arg2;
        String extName = url.getParameter("proxy", "javassist");
        if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
        org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
        return extension.getInvoker(arg0, arg1, arg2);
    }
}

(Protocol)ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension() 获得的类如下:

package org.apache.dubbo.rpc;
import org.apache.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adaptive implements org.apache.dubbo.rpc.Protocol {
    // 没有 @Adaptive 注解的方法会直接抛出异常
    public void destroy()  {
        throw new UnsupportedOperationException("The method public abstract void org.apache.dubbo.rpc.Protocol.destroy() of interface org.apache.dubbo.rpc.Protocol is not adaptive method!");
    }

    public int getDefaultPort()  {
        throw new UnsupportedOperationException("The method public abstract int org.apache.dubbo.rpc.Protocol.getDefaultPort() of interface org.apache.dubbo.rpc.Protocol is not adaptive method!");
    }
    
    // 有 Adaptive 注解的方法都会生成动态方法
    public org.apache.dubbo.rpc.Exporter export(org.apache.dubbo.rpc.Invoker arg0) throws org.apache.dubbo.rpc.RpcException {
        // 参数异常检查
        if (arg0 == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument == null");
        if (arg0.getUrl() == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument getUrl() == null");
        
        // 这里使用的是 url 中的 protocol 作为动态获取的类名,如果 url 中没有,则使用默认的类名
        org.apache.dubbo.common.URL url = arg0.getUrl();
        String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
        if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.Protocol) name from url (" + url.toString() + ") use keys([protocol])");

        org.apache.dubbo.rpc.Protocol extension = (org.apache.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.Protocol.class).getExtension(extName);
        return extension.export(arg0);
    }

    public org.apache.dubbo.rpc.Invoker refer(java.lang.Class arg0, org.apache.dubbo.common.URL arg1) throws org.apache.dubbo.rpc.RpcException {
        if (arg1 == null) throw new IllegalArgumentException("url == null");

        org.apache.dubbo.common.URL url = arg1;
        String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
        if(extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.Protocol) name from url (" + url.toString() + ") use keys([protocol])");

        org.apache.dubbo.rpc.Protocol extension = (org.apache.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.Protocol.class).getExtension(extName);
        return extension.refer(arg0, arg1);
    }

    public java.util.List getServers()  {
        throw new UnsupportedOperationException("The method public default java.util.List org.apache.dubbo.rpc.Protocol.getServers() of interface org.apache.dubbo.rpc.Protocol is not adaptive method!");
    }
}

通过 SPI 获取到了 Type 接口的 AdaptiveClass,接下来看在使用的地方如何动态获取指定的类。

暴露服务到 jvm 本地

代码很短小,实际运行的内容却不简单

private void exportLocal(URL url) {
    // 设置 local URL 属性
    URL local = URLBuilder.from(url).setProtocol("injvm").setHost("127.0.0.1").setPort(0).build();
    Exporter exporter = PROTOCOL.export(PROXY_FACTORY.getInvoker(this.ref, this.interfaceClass, local));
    // ...
}

通过前面已经知道 PROXY_FACTORY 是动态生成ProxyFactory$Adaptive 类的实例,
PROXY_FACTORY.getInvoker(this.ref, this.interfaceClass, local) 会调用ProxyFactory$Adaptive 类的下面几行代码

org.apache.dubbo.common.URL url = arg2;
// 为 local 的 URL 中 proxy 参数为空,会去获取名为 javassist 的默认实现类
String extName = url.getParameter("proxy", "javassist");
// 这里根据运行时得到的名称加载指定类实例
org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory)ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
// 调用类实例的 getInvoker() 方法
return extension.getInvoker(arg0, arg1, arg2);

getExtension(extName) 方法调用逻辑如下


ExtensionLoader 类加载指定类.png

PROXY_FACTORY.getInvoker(this.ref, this.interfaceClass, local) 实际调用栈如下

ProxyFactory的getInvoker.png

接着是 PROTOCOL.export(invoker) 分析过程与 PROXY_FACTORY.getInvoker(...) 一致,它的调用栈逻辑如下

Protocal的export.png

你可能感兴趣的:(Dubbo SPI 使用源码分析)