Dubbo SPI 学习笔记

What is SPI

SPI(Service Provider Interface),是一种服务发现机制。通俗地说,就是在系统运行时,能够指定接口选择哪一个实现类。

Java SPI

SPI全称Service Provider Interface,是Java提供的一套用来被第三方实现或者扩展的接口,它可以用来启用框架扩展和替换组件。 SPI的作用就是为这些被扩展的API寻找服务实现。

SPI和API区别

      SPI (Service Provider Interface)调用方来制定接口规范,提供给外部来实现,调用方在调用时则选择自己需要的外部实现。  从使用人员上来说,SPI 被框架扩展人员使用。

       API (Application Programming Interface)在大多数情况下,都是实现方制定接口并完成对接口的实现,调用方仅仅依赖接口调用,且无权选择不同实现。 从使用人员上来说,API 直接被应用开发人员使用。

SPI的简单实现

1. 定义一个接口与对应的方法

public interface PrintService {
    /**
     * print
     */
    void printInfo();
}

2. 编写一个该接口的实现类

public class PrintServiceImpl implements PrintService {

    @Override
    public void printInfo() {
        System.out.println("Hello World");
    }
}

3. 在resources目录下新建META-INF/services目录,创建一个以接口全路径名命名的文件,如com.test.PrintService

4. 文件内容为具体的实现类的全路径名,如果有多个,则用分行符分割。如com.test.impl.PrintServiceImpl

5. 在代码中通过java.util.ServiceLoader加载具体的实现类

    public static void main(String[] args) {
        ServiceLoader<PrintService> serviceServiceLoader = ServiceLoader.load(PrintService.class);
        for (PrintService printService : serviceServiceLoader) {
            printService.printInfo();
        }
    }

SPI 原理解析

源码见ServiceLoader类。

SPI加载的主要流程

1. 根据传入的Service类型,创建一个新的ServiceLoader对象

    
    /**
     * Creates a new service loader for the given service type, using the
     * current thread's {@linkplain java.lang.Thread#getContextClassLoader
     * context class loader}.
     */
    public static <S> ServiceLoader<S> load(Class<S> service) {
        // 获取当前线程的类加载器
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }
    
    public static <S> ServiceLoader<S> load(Class<S> service,ClassLoader loader) {
        return new ServiceLoader<>(service, loader);
    }

2. 创建新的 LazyIterator

    private ServiceLoader(Class<S> svc, ClassLoader cl) {
        service = Objects.requireNonNull(svc, "Service interface cannot be null");
        loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
        reload();
    }

    public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);
    }

LazyIterator

扫描(包括所有引用的jar 包里的)META_INF/services/目录下的配置文件并解析配置中的所有service的名字。

        private boolean hasNextService() {
            if (nextName != null) {
                return true;
            }
            if (configs == null) {
                try {
                    String fullName = PREFIX + service.getName();
                    if (loader == null)
                        configs = ClassLoader.getSystemResources(fullName);
                    else
                        configs = loader.getResources(fullName);
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            while ((pending == null) || !pending.hasNext()) {
                if (!configs.hasMoreElements()) {
                    return false;
                }
                pending = parse(service, configs.nextElement());
            }
            nextName = pending.next();
            return true;
        }

3. 将配置文件中的全路径名,通过反射加载实例化并放到缓存中

        private S nextService() {
            if (!hasNextService())
                throw new NoSuchElementException();
            String cn = nextName;
            nextName = null;
            Class<?> c = null;
            try {
                c = Class.forName(cn, false, loader);
            } catch (ClassNotFoundException x) {
                fail(service,
                     "Provider " + cn + " not found");
            }
            if (!service.isAssignableFrom(c)) {
                fail(service,
                     "Provider " + cn  + " not a subtype");
            }
            try {
                S p = service.cast(c.newInstance());
                providers.put(cn, p);
                return p;
            } catch (Throwable x) {
                fail(service,
                     "Provider " + cn + " could not be instantiated",
                     x);
            }
            throw new Error();          // This cannot happen
        }

Java SPI 缺点

  1. 一次性实例化扩展点所有实现,如果有扩展实现,则初始化很耗时;如果没用上也加载,则浪费资源
  2. 配置文件中只是简单的列出了所有的扩展实现,而没有给他们命名。导致在程序中很难去准确的引用它们
  3. 扩展如果依赖其他的扩展,做不到自动注入和装配
  4. 展很难和其他的框架集成,比如扩展里面依赖了一个Spring bean,原生的Java SPI不支持

Dubbo SPI

在Java SPI的基础上进行了增强。

关键概念

  1. 扩展点:接口
  2. 扩展:接口的实现
  3. 自动包装、自动加载、自适应、自动激活
  4. 注解:@SPI  、@Adaptive、@Active

 原理解析

通过ExtensionLoader加载指定的实现类。Dubbo SPI所需的配置文件放置在META-INF/dubbo的路径下。

配置模板:key-value结构

printServiceImpl=com.test.PrintService

简单实现

    @Test
    public void dubboSPITest() {
        ExtensionLoader<PrintService> extensionLoader = ExtensionLoader.getExtensionLoader(PrintService.class);
        PrintService printServiceImpl = extensionLoader.getExtension("printServiceImpl");
        printServiceImpl.printInfo();
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

参考:

http://dubbo.apache.org/zh-cn/docs/source_code_guide/dubbo-spi.html

https://www.cnblogs.com/williamjie/p/11096605.html

https://www.cnblogs.com/jy107600/p/11464985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿神面试题

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值