dubbo源码分析之SPI机制(二)

在上一篇文章中dubbo源码分析之SPI机制介绍了dubbo的spi机制中的ExtensionLoader的源码,本篇文章将继续深入研究这个dubbo spi底层类的实现。

扩展点自适应(Adaptive)
ExtensionLoader 注入的依赖扩展点是一个 Adaptive 实例,直到扩展点方法执行时才决定调用是一个扩展点实现

使用getAdaptiveExtension()这个方法获取扩展点自适应

@SuppressWarnings("unchecked")
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;
}

createAdaptiveExtension()方法有两个作用:
1、获取扩展点自适应的Class对象并实例化
2、对实例内的set方法进行自动注入

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

先看第一个部分:getAdaptiveExtensionClass()

private Class getAdaptiveExtensionClass() {
        // 获取当前扩展点的所有class对象,这个方法会调用loadExtensionClasses()
    getExtensionClasses();
    if (cachedAdaptiveClass != null) {
        return cachedAdaptiveClass;
    }
    return cachedAdaptiveClass = createAdaptiveExtensionClass();
}

private Map> loadExtensionClasses() {
        // 获取接口上SPI注解的value值,这个是默认的扩展点实现名称
    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];
        }
    }

        // 通过调用loadFile,加载如下三个路径的接口扩展点声明文件
    Map> extensionClasses = new HashMap>();
    loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
    loadFile(extensionClasses, DUBBO_DIRECTORY);
    loadFile(extensionClasses, SERVICES_DIRECTORY);
    return extensionClasses;
}

// 加载接口扩展点和包装类
private void loadFile(Map> extensionClasses, String dir) {
    // 加载type类型指定名称的接口扩展点声明文件
    String fileName = dir + type.getName();
    try {
        Enumeration 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) {
                            // 获取行内容,去掉注释内容,其中格式为name=com.foo.Impl
                            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('=');
                                    if (i > 0) {
                                         // 扩展点名称
                                        name = line.substring(0, i).trim();  
                                        // 扩展点实现类全限定名称
                                        line = line.substring(i + 1).trim();
                                    }
                                    if (line.length() > 0) {
                                        // 加载扩展点实现类Class
                                        Class clazz = Class.forName(line, true, classLoader);
                                        // 必须是interface,否则抛出异常
                                        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.");
                                        }
                                        // 如果扩展点使用Adaptive注解了,这就是自适应扩展点,要求只有一个扩展点能使用Adaptive注解
                                        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 {
                                                // 这里是判断是否为包装类的关键点,如果调用getConstructor抛出异常,说明是扩展点实现,否则说明是扩展点的包装类
                                                clazz.getConstructor(type);
                                                Set> wrappers = cachedWrapperClasses;
                                                if (wrappers == null) {
                                                    cachedWrapperClasses = new ConcurrentHashSet>();
                                                    wrappers = cachedWrapperClasses;
                                                }                                                                                                                  
                                                wrappers.add(clazz);
                                            } catch (NoSuchMethodException e) {
                                                clazz.getConstructor();
                                                if (name == null || name.length() == 0) {
                                                    // 如果名称是空,判断Extension注解的名称,如果这个名称也是空,则使用扩展点实现名称,比如j接口GreetService的扩展点是GreetServiceHello,使用hello作为扩展点名称
                                                    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);
                                                        }
                                                    }
                                                }
                                                // 对于普通扩展点,加入到map缓存中,如果使用了Activate注解缓存到cacheActivates中
                                                String[] names = NAME_SEPARATOR.split(name);
                                                if (names != null && names.length > 0) {
                                                    Activate activate = clazz.getAnnotation(Activate.class);
                                                    if (activate != null) {
                                                        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);
                                                        } 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);
    }
}

至此我们已经明白了扩展点加载的过程,回到getAdaptiveExtensionClass这个方法,
它调用了createAdaptiveExtensionClass

private Class getAdaptiveExtensionClass() {
        // 加载扩展点class
    getExtensionClasses();
        // 执行上面的方法时,如果有扩展点使用了Adaptive注解,则直接返回cachedAdaptiveClass
    if (cachedAdaptiveClass != null) {
        return cachedAdaptiveClass;
    }
        // 如果没有扩展点使用Adaptive,系统使用Javassist生成
    return cachedAdaptiveClass = createAdaptiveExtensionClass();
}

// 使用javassist生成自适应扩展动态class
private Class createAdaptiveExtensionClass() {
    String code = createAdaptiveExtensionClassCode();

        // 使用Javassist加载生成的动态自适应扩展点
    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,这个方法很长,我这里就不贴出代码,简单说明一下这个方法的作用:
1、要求接口中必须至少一个方法使用了Adpative注解,否则不生成自适应扩展点
2、实现扩展点接口的方法,如果方法没有使用Adaptive,方法体内直接抛出异常
3、Adaptive注解的方法,需要手动实现,Dubbo 使用 URL 对象(包含了Key-Value)传递配置信息。扩展点方法调用会有URL参数(或是参数有URL成员)这样依赖的扩展点也可以从URL拿到配置信息,所有的扩展点自己定好配置的Key后,配置信息从URL上从最外层传入。URL在配置传递上即是一条总线。
如下是dubbo的Protocol协议接口的自适应扩展点生成的代码,这是我通过断点调试拷贝出来的。
可以看出如果Adaptive中如果没有设置扩展点,默认使用dubbo扩展

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

自适应扩展点加载成功之后,需要对扩展点的set方法进行自动注入,调用方法injectExtension,其中使用了objectFactory对象,这个对象是在ExtensionLoader初始化的时候生成的ExtensionFactory自适应扩展点,这里默认是spring注入

objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());

private T injectExtension(T instance) {
    try {
        if (objectFactory != null) {
            for (Method method : instance.getClass().getMethods()) {
                // 注入setter方法
                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;
}

指定名称获取扩展点
使用getExtension(name)获取指定名称的扩展点实现,这个和自适应扩展点类似,有点不同的地方是实例化的时候,同时会实例化包装类

public T getExtension(String name) {
        if (name == null || name.length() == 0)
            throw new IllegalArgumentException("Extension name == null");
        if ("true".equals(name)) {
            return getDefaultExtension();
        }
        Holder holder = cachedInstances.get(name);
        if (holder == null) {
            cachedInstances.putIfAbsent(name, new Holder());
            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;
    }

private T createExtension(String name) {
        // 根据名称获取扩展点class对象
    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);
        }
                // 注入实例的setter方法
        injectExtension(instance);
        Set> 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的设计非常经典,前后用了两篇文章才把这个点说明白,设计者使用了大量的缓存、注解、动态注入等机制,扩展点是在运行期才确定的,这样的插件式设计对调用者是屏蔽的,调用者以及spi插件的开发者只需要关注业务实现以及正确使用注解即可。

由于这一部分非常复杂,也是dubbo插拔式设计的内核,所以对于想了解dubbo源码的朋友来说,研究dubbo的spi机制是不可避免的,否则在调试以及学习过程中容易迷失。

个人感觉,dubbo的spi自适应扩展点能够在方法级别进行扩展,解决了java动态代理或者多态只有接口级别“缺陷”。

你可能感兴趣的:(dubbo源码分析之SPI机制(二))