Dubbo剖析-SPI机制

文章要点:

  1、什么是SPi

  2、Dubbo为什么要实现自己的SPi

  3、Dubbo的IOC和AOP

  4、Dubbo的Adaptive机制

  5、Dubbo动态编译机制

  6、Dubbo与Spring的融合

  一、什么是SPI

  SPI 全称为 (Service Provider Interface) ,是JDK内置的一种服务提供发现机制。SPI是一种动态替换发现的机制。我们经常遇到的就是java.sql.Driver接口,不同的数据库不同的Driver实现。

  如何应用?

  当服务的提供者提供了一种接口的实现之后,需要在classpath下的META-INF/services/目录里创建一个以服务接口命名的文件,这个文件里的内容就是这个接口的具体的实现类。当程序需要这个服务的时候,调                                    java.util.ServiceLoader加载spi配置文件即可获取spi文件里所有的实现类。

  举例说明
  mysql
  在mysql-connector-java-5.1.45.jar中,META-INF/services目录下会有一个名字为java.sql.Driver的文件:

  
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver

  驱动加载

  DriverManager

static {
    loadInitialDrivers();
    println("JDBC DriverManager initialized");
}

//loadInitialDrivers
AccessController.doPrivileged(new PrivilegedAction<Void>() {
    public Void run() {
        ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
        Iterator<Driver> driversIterator = loadedDrivers.iterator();

  二、dubbo为什么实现自己的spi

  1、JDK会加载所有的SPI,资源浪费
  2、JDK的SPI不支持缓存
  3、JDK的SPI通过for循环进行加载,,DUbbo支持通过Key进行获取SPI对象
  三、Dubbo的Adapative机制
  Adapative如字面意思,适配的类。Dubbo的SPI入口
  Adaptive如字面意思,适配的类。dubbo的spi入口ExtensionLoader.getExtensionLoader,当我们传入type,ExtensionLoader扫描对应的spi文件,如果类加@Adaptive注解则直接返回,反之自动生成对应适配类。
  调用ExtensionLoader的地方有多个,下面列两个,有兴趣的可以自己跟踪下代码
  
//com.alibaba.dubbo.container.Main 启动入口
private static final ExtensionLoader<Container> loader = ExtensionLoader.getExtensionLoader(Container.class);
//com.alibaba.dubbo.config.ServiceConfig
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

调用链路

  |--ExtensionLoader.getAdaptiveExtension
  |----ExtensionLoader.createAdaptiveExtension
  |------ExtensionLoader.injectExtension
  |--------ExtensionLoader.getAdaptiveExtensionClass
  |----------ExtensionLoader.getExtensionClasses
  |------------ExtensionLoader.loadExtensionClasses
  |--------------ExtensionLoader.loadFile
  |----------ExtensionLoader.createAdaptiveExtensionClass
  getAdaptiveExtensionClass,获取Adaptive适配类,返回 cachedAdaptiveClass,这个在 spi加载的时候会提取出来并缓存到cachedAdaptiveClass,如果没有Adaptive类则自动生成
  先看下getExtensionClasses调用的loadExtensionClasses的实现逻辑
  
private Map<String, Class<?>> loadExtensionClasses() {
    final SPI defaultAnnotation = type.getAnnotation(SPI.class);
    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];
        }
    }
    
    //将所有的spi缓存到extensionClasses
    Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
    loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
    loadFile(extensionClasses, DUBBO_DIRECTORY);
    loadFile(extensionClasses, SERVICES_DIRECTORY);
    return extensionClasses;
}

loadFile

加载对应路径下的spi文件里的class并存储到缓存变量里

加载的路径

DUBBO_INTERNAL_DIRECTORY = META-INF/dubbo/internal/
DUBBO_DIRECTORY = META-INF/dubbo/
SERVICES_DIRECTORY = META-INF/services/

文件名

目录 + type.getName();

三个缓存变量

  

cachedAdaptiveClass
如果这个class含有adaptive注解就赋值,例如ExtensionFactory,而例如Protocol在这个环节是没有的。
cachedWrapperClasses
只有当该class无adative注解,并且构造函数包含目标接口(type)类型,例如protocol里面的spi就只有ProtocolFilterWrapper和ProtocolListenerWrapper能命中
cachedActivates
剩下的类,类有Activate注解
cachedNames
剩下的类就存储在这里

代码视图

  

private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
    //省略若干代码

    Class<?> clazz = Class.forName(line, true, classLoader);
    
    //查看类或方法是否包含Adaptive注解,如:AdaptiveExtensionFactory
    if (clazz.isAnnotationPresent(Adaptive.class)) {
        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 {
        try {
            //判断该类是否有type参数的构造方法,如ProtocolFilterWrapper,ProtocolListenerWrapper
            clazz.getConstructor(type);
            Set<Class<?>> wrappers = cachedWrapperClasses;
            if (wrappers == null) {
                cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
                wrappers = cachedWrapperClasses;
            }
            //添加到 cachedWrapperClasses
            wrappers.add(clazz);
        } catch (NoSuchMethodException e) {
            clazz.getConstructor();
            if (name == null || name.length() == 0) {
                //spi没有key的情况下, 读取注解名
                name = findAnnotationName(clazz);
                if (name == null || name.length() == 0) {
                    if (clazz.getSimpleName().length() > type.getSimpleName().length()
                            && clazz.getSimpleName().endsWith(type.getSimpleName())) {
                        //读取 simpleName的一部分作为name  如 com.alibaba.dubbo.rpc.protocol.http.HttpProtocol
                        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 activate = clazz.getAnnotation(Activate.class);
                if (activate != null) {
                    cachedActivates.put(names[0], activate);
                }
                for (String n : names) {
                    if (!cachedNames.containsKey(clazz)) {
                        //上面的逻辑如果都没有符合的,加入到 cachedNames
                        cachedNames.put(clazz, n);
                    }
                    Class<?> c = extensionClasses.get(n);
                    if (c == null) {
                        extensionClasses.put(n, clazz);
                    } else if (c != clazz) {
                        throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
                    }
                }
            }
        }
    }

    //省略若干代码
}
经过spi文件的加载,对应的class都已经缓存,最后调用ExtensionLoader.getAdaptiveExtension返回,getAdaptiveExtension方法会判断 cachedAdaptiveInstance 是否为空如果不为空则返回反之则生成对应的 Adaptive类,生成逻辑见下方第五小节。
四、 dubbo 的IOC和AOP
  
private T createExtension(String name) {
    //从缓存里获取class
    Class<?> clazz = getExtensionClasses().get(name);
    if (clazz == null) {
        throw findException(name);
    }
    try {
        //从缓存获取class实例
        T instance = (T) EXTENSION_INSTANCES.get(clazz);
        if (instance == null) {
            EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
            instance = (T) EXTENSION_INSTANCES.get(clazz);
        }
        //模仿spring做的IOC注入
        injectExtension(instance);

        Set<Class<?>> wrapperClasses = cachedWrapperClasses;
        if (wrapperClasses != null && wrapperClasses.size() > 0) {
            for (Class<?> wrapperClass : wrapperClasses) {
                //对instance进行包装,这里使用到aop
                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);
    }
}

createExtension
从cachedClasses 获得class名

EXTENSION_INSTANCES 实例对象缓存

getExtension(String name)返回的是 get出来的对象wrapper对象,例如protocol就是ProtocolFilterWrapper和ProtocolListenerWrapper其中一个。

injectExtension(T instance)//dubbo的IOC反转控制,就是从spi或spring 容器里面获取对象并赋值

IOC
  dubbo的IOC反转控制,就是从spi和spring里面提取对象赋值。
  |--injectExtension(T instance)
  |----objectFactory.getExtension(pt, property)
  |------SpiExtensionFactory.getExtension(type, name)
  |--------ExtensionLoader.getExtensionLoader(type)
  |--------loader.getAdaptiveExtension()
  |------SpringExtensionFactory.getExtension(type, name)
  |--------context.getBean(name)
  
private T injectExtension(T instance) {
    try {
        if (objectFactory != null) {
            for (Method method : instance.getClass().getMethods()) {
                //获取set开头的方法
                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) : "";
                        //获取对应的对象,这里有SpringExtensionFactory 和 SpiExtensionFactory两种实现
                        //如果SpiExtensionFactory不支持的则通过SpringExtensionFactory 从spring容器中获取实例对象
                        Object object = objectFactory.getExtension(pt, property);
                        if (object != null) {
                            //set注入
                            method.invoke(instance, object);
                        }
    //省略部分代码
    return instance;
}

AOP

  AOP的简单设计, createExtension的aop代码实现

  

//这里获取当前spi下所有 包装类型,这里其实就是一个装饰者模式的运用,可以参考ProtocolFilterWrapper
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
    for (Class<?> wrapperClass : wrapperClasses) {
        //将instance装饰完成后返回
        instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
    }
}
。

五、dubbo的动态编译

  以 Protocol的spi 举例子

  

com.alibaba.dubbo.config.ServiceConfig
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
|--ExtensionLoader.getAdaptiveExtensionClass
|----ExtensionLoader.createAdaptiveExtensionClass
|------ExtensionLoader.createAdaptiveExtensionClassCode
private Class<?> getAdaptiveExtensionClass() {
    getExtensionClasses();

    //如果缓存里有 Adaptive类则直接返回
    if (cachedAdaptiveClass != null) {
        return cachedAdaptiveClass;
    }

    //如果没有Adaptive类,就自动生成
    return cachedAdaptiveClass = createAdaptiveExtensionClass();
}

private Class<?> createAdaptiveExtensionClass() {
    //生成类 代码文本
    String code = createAdaptiveExtensionClassCode();
    ClassLoader classLoader = findClassLoader();

    //获取Compiler的spi 类
    com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();

    //编译代码  default=javassist
    return compiler.compile(code, classLoader);
}

createAdaptiveExtensionClassCode
主要生成 Protocol 的 Adaptive类java代码,Protocol的默认协议是 dubbo

@SPI("dubbo")
public interface Protocol {
只对Protocol带有 @Adaptive 注解的方法写入实现体,其它方法的实现则抛出异常,生成的代码样例如下
package com.alibaba.dubbo.rpc;

import com.alibaba.dubbo.common.extension.ExtensionLoader;

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

        //提取url里的协议,如果为空则使用默认协议 dubbo 。 该行注释不是生成出来的。       
        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);
    }

最后调用 JavassistCompiler.compile 方法进行编译,需要将java源码编译成二进制class并利用classloader加载至内存,这样我们的程序才能调用这个类。

六、dubbo与spring的融合

  容器的启动
  com.alibaba.dubbo.container.Main
  dubbo启动入口, Container的默认策略是spring

  

spring=com.alibaba.dubbo.container.spring.SpringContainer

main方法的实现体会调用 SpringContainer.start方法,方法的实现体就是常规的spring容器使用姿势

public void start() {
    String configPath = ConfigUtils.getProperty(SPRING_CONFIG);
    if (configPath == null || configPath.length() == 0) {
        configPath = DEFAULT_SPRING_CONFIG;
    }
    context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+"));
    context.start();
}

dubbo schema<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://code.alibabatech.com/schema/dubbo        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">


    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="hello-world-app"/>

    <!-- 使用multicast广播注册中心暴露服务地址 -->
    <dubbo:registry address="zookeeper://127.0.0.1:2181" check="false" client="zkclient" />

    <!-- 用dubbo协议在20880端口暴露服务 -->
    <dubbo:protocol name="dubbo" port="20880"/>

    <!-- 声明需要暴露的服务接口 -->
    <dubbo:service interface="com.youzan.dubbo.api.DemoService"
                   class="com.youzan.dubbo.provider.DemoServiceImpl"/>

</beans>
这是一个常见的dubbo服务 xml,这些dubbo标签是对spring的拓展。
spring的拓展约定,需要有三个文件
dubbo.xsd 定义 dubbo xml标签及xml节点约定
spring.schemas 定义 namespace和xsd的对应关系
spring.handlers 指定 namespace的xml解析类

spring.handlers的文件内容

http://code.alibabatech.com/schema/dubbo=com.alibaba.dubbo.config.spring.schema.DubboNamespaceHandler
public class DubboNamespaceHandler extends NamespaceHandlerSupport { static { Version.checkDuplicate(DubboNamespaceHandler.class); } public void init() { registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true)); registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true)); registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true)); registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true)); registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true)); registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true)); registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); } }

这里的各个标签对应都有对应的 parser,在parse方法里,走的spring的一套,将xml信息组装成BeanDefinition返回,接着由spring容器把对应的类进行实例化。

猜你喜欢

转载自www.cnblogs.com/hanxue112253/p/10070054.html