目录

前言

Java SPI

API VS SPI

使用场景

Java SPI使用步骤

示例代码

ServiceLoader源码分析

Java SPI小结

ShardingSphere 中的SPI实战


前言

(3)窥探ShardingSphere 架构设计(可插拔架构)_RichardGeek的博客_shardingsphere 架构窥探ShardingSphere 架构设计(可插拔架构)上文中 针对“ShardingSphere 插件化” 可插拔化设计中重复使用了Java SPI的方式。本文较细节的展开说明。

Java SPI

        官方介绍:https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html

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

API VS SPI

  • API (Application Programming Interface)在大多数情况下,都是实现方制定接口并完成对接口的实现,调用方仅仅依赖接口调用,且无权选择不同实现。 从使用人员上来说,API 直接被应用开发人员使用。
  • SPI (Service Provider Interface)是调用方来制定接口规范,提供给外部来实现,调用方在调用时则选择自己需要的外部实现。 从使用人员上来说,SPI 被框架扩展人员使用。

SPI整体机制图如下:

Java SOP 可插拔 模块化 java插拔式设计架构_类加载器

本质上Java SPI 实际上是利用“基于接口的编程+策略模式+配置文件”组合实现的思想动态加载机制。 

        系统设计的各个抽象,往往有很多不同的实现方案,在面向的对象的设计里,一般推荐模块之间基于接口编程,模块之间不对实现类进行硬编码。

        一旦代码里涉及具体的实现类,就违反了可拔插的原则,如果需要替换一种实现,就需要修改代码。为了实现在模块装配的时候能不在程序里动态指明,这就需要一种服务发现机制。
Java SPI就是提供这样的一个机制:为某个接口寻找服务实现的机制。有点类似IOC的思想,就是将装配的控制权移到程序之外,在模块化设计中这个机制尤其重要。

        所以SPI的核心思想就是方便模块化构建代码、解耦。

使用场景

概括地说,适用于:调用者根据实际使用需要,启用、扩展、或者替换框架的实现策略。

比较常见的例子:

  • 数据库驱动加载接口实现类的加载,JDBC加载不同类型数据库的驱动。可见是利用SPI机制来获取并加载驱动提供类(java.sql.Driver接口的实现类)。以MySQL JDBC驱动为例,在其META-INF/services目录下找到名为java.sql.Driver的文件,且其中的内容是com.mysql.jdbc.Driver。
  • 日志门面接口实现类加载,SLF4J加载不同提供商的日志实现类。 slf4j是一个典型的门面接口,早起我们使用log4j作为日记记录框架,我们需要同时引入slf4j和log4j的依赖。后面比较流行logback,我们也想要把项目切换到logback上来,此时利用SPI的机制,我们只需要把log4j的jar包替换为logback的jar包就可以了
  • Spring,Spring中大量使用了SPI,比如:对servlet3.0规范对ServletContainerInitializer的实现、自动类型转换Type Conversion SPI(Converter SPI、Formatter SPI)等
  • Dubbo,Dubbo中也大量使用SPI的方式实现框架的扩展, 不过它对Java提供的原生SPI做了封装,允许用户扩展实现Filter接口。 

Java SPI使用步骤

要使用Java SPI,需要遵循如下约定:

  • 当服务提供者提供了接口的一种具体实现后,在jar包的META-INF/services目录下创建一个以“接口全限定名”为命名的文件,内容为实现类的全限定名;
  • 接口实现类所在的jar包放在主程序的classpath中;
  • 主程序通过java.util.ServiceLoder动态装载实现模块,它通过扫描META-INF/services目录下的配置文件找到实现类的全限定名,把类加载到JVM;
  • SPI的实现类必须携带一个不带参数的构造方法;

示例代码

step1. 定义接口

package com.renrenche.business.spi;

/**
 * @Classname HumanTestSPI
 * @Date 2022/7/7 下午12:53
 * @Created by liuchao58
 * @Description TODO
 */
public interface HumanTestSPI {
   public void speak();
}

step2. 定义实现类

package com.renrenche.business.spi;

/**
 * @Classname Chinese
 * @Date 2022/7/7 下午12:54
 * @Created by liuchao58
 * @Description TODO
 */
public class Chinese implements HumanTestSPI {
    @Override
    public void speak() {
        System.out.println("中国话");
    }
}

---------
package com.renrenche.business.spi;

/**
 * @Classname English
 * @Date 2022/7/7 下午12:55
 * @Created by liuchao58
 * @Description TODO
 */
public class English implements HumanTestSPI{
    @Override
    public void speak() {
        System.out.println("English....");
    }
}

step3. 定义配置文件

在classpath(src/main/resources)下创建META-INF/resources目录,创建以接口名字com.renrenche.business.spi.HumanTestSPI命名的文件,内容写入接口实现类的全限定类名,如果有多个需换行

com.renrenche.business.spi.Chinese
com.renrenche.business.spi.English

如下图所示

Java SOP 可插拔 模块化 java插拔式设计架构_类加载器_02

step4. 执行ServiceLoader 加载 & step5. 查看结果输出

public static void main(String[] args) {
        ServiceLoader<HumanTestSPI> loadHumanTestSPI = ServiceLoader.load(HumanTestSPI.class);
        for (HumanTestSPI humanTestSPI:loadHumanTestSPI){
            humanTestSPI.speak();
        }

    }

 如下图所示:

Java SOP 可插拔 模块化 java插拔式设计架构_大数据_03

ServiceLoader源码分析


ServiceLoader(ps:java.util.ServiceLoader 自己可以打开源码研读)在这里没有核心操作,主要负责对外提供load()方法用于获取SPI接口和实例化懒加载迭代器LazyIterator。


public final class ServiceLoader<S> implements Iterable<S>{
    
    #SPI规则固定加载文件地址前缀
    private static final String PREFIX = "META-INF/services/";
       #SPI的接口
    private final Class<S> service;
    #类加载器,使用的是当前线程的类加载器(Thread.currentThread().getContextClassLoader())
    private final ClassLoader loader;
    #默认是null, 创建ServiceLoader时采用的访问控制上下文
    private final AccessControlContext acc;
    #缓存加载成功的类
    private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
    #当前的迭代器,默认初始化为LazyIterator,注意这里是懒加载的,只有使用的时候才去迭代加载SPI文件
    private LazyIterator lookupIterator;
    
    #SPI执行使用方法,不指定ClassLoader
       public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }
    #SPI执行使用方法,指定ClassLoader
    public static <S> ServiceLoader<S> load(Class<S> service,ClassLoader loader){
        return new ServiceLoader<>(service, loader);
    }
    #构造方法中保存SPI接口,初始化懒加载迭代器
    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);
    }
}

在指定配置的情况下,ServiceLoader.load 根据传入的接口类,遍历 META-INF/services 目录下的以该类命名的文件中的所有类,然后再用类加载器加载这些服务。 

Java SOP 可插拔 模块化 java插拔式设计架构_大数据_04

类加载器加载
        获取到 SPI 服务实现类的文件之后,就可以使用类加载器将对应的类加载到内存中, 问题在于,SPI 的接口是 Java 核心库的一部分,是由引导类加载器来加载的;SPI 实现的 Java 类一般是由系统类加载器来加载的。引导类加载器是无法找到 SPI 的实现类的,因为它只加载 Java 的核心库。它也不能代理给系统类加载器,因为它是系统类加载器的祖先类加载器。也就是说,类加载器的双亲委派模型无法解决这个问题。

线程上下文类加载器。破坏了“双亲委派模型”,可以在执行线程中抛弃双亲委派加载链模式,使程序可以逆向使用类加载器,从而实现 SPI 服务的加载。线程上下文类加载器的实现如下:

  1. 在 ThreaLocal 中通过 setContextClassLoader(ClassLoader cl)存储当前线程中的类加载器,默认为 AppClassLoader。
  2. Java 核心库中的程序在需要加载 SPI 实现类的时候,会首先通过 ThreaLocal 中的 getContextClassLoader(ClassLoader cl)方法获取上下文类加载器,然后通过该类加载器加载 SPI 的实现类。

具体代码&官方英文注释如下:【注释说的很明确清晰也很重要哦】

/**
     * Creates a new service loader for the given service type, using the
     * current thread's {@linkplain java.lang.Thread#getContextClassLoader
     * context class loader}.
     *
     * <p> An invocation of this convenience method of the form
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>)</pre></blockquote>
     *
     * is equivalent to
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>,
     *                    Thread.currentThread().getContextClassLoader())</pre></blockquote>
     *
     * @param  <S> the class of the service type
     *
     * @param  service
     *         The interface or abstract class representing the service
     *
     * @return A new service loader
     */
    public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }
/**
     * Creates a new service loader for the given service type and class
     * loader.
     *
     * @param  <S> the class of the service type
     *
     * @param  service
     *         The interface or abstract class representing the service
     *
     * @param  loader
     *         The class loader to be used to load provider-configuration files
     *         and provider classes, or <tt>null</tt> if the system class
     *         loader (or, failing that, the bootstrap class loader) is to be
     *         used
     *
     * @return A new service loader
     */
    public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader)
    {
        return new ServiceLoader<>(service, loader);
    }

LazyIterator是懒加载,实例化后什么也不干,只保存了SPI接口

private class LazyIterator implements Iterator<S> {
        private LazyIterator(Class<S> service, ClassLoader loader) {
            this.service = service;
            this.loader = loader;
        }
    }

ServiceLoader的iterator()方法被调用,开始执行核心逻辑LazyIterator懒加载SPI文件

  • hasNextService():用于加载META-INF/services/下SPI文件
  • nextService():用于根据SPI文件中指定的实现类的全限定类名通过反射实例化对象,放入缓存
private class LazyIterator implements Iterator<S> {
        
        private boolean hasNextService() {
            if (nextName != null) {
                return true;
            }
            if (configs == null) {
                try {
                    #拼装SPI文件完整地址META-INF/services+SPI全限定类名
                    String fullName = PREFIX + service.getName();
                    if (loader == null)
                        configs = ClassLoader.getSystemResources(fullName);
                    else
                        #加载SPI文件
                        configs = loader.getResources(fullName);
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            while ((pending == null) || !pending.hasNext()) {
                if (!configs.hasMoreElements()) {
                    return false;
                }
                #解析SPI文件,获取实现类全限定类名
                pending = parse(service, configs.nextElement());
            }
            #赋值实现类全限定类名
            nextName = pending.next();
            return true;
        }

        private S nextService() {
            if (!hasNextService())
                throw new NoSuchElementException();
            String cn = nextName;
            nextName = null;
            Class<?> c = null;
            try {
                #根据全限定类名获取Class描述文件
                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 {
                #根据Class文件使用反射创建对象
                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小结

优点:
        使用Java SPI机制的优势是实现解耦,使得第三方服务模块的装配控制的逻辑与调用者的业务代码分离,而不是耦合在一起。应用程序可以根据实际业务情况启用框架扩展或替换框架组件。

        相比使用提供接口jar包,供第三方服务模块实现接口的方式,SPI的方式使得源框架不必关心接口的实现类的路径

缺点:

        虽然ServiceLoader也算是使用的延迟加载,但是基本只能通过遍历全部获取,也就是接口的实现类全部加载并实例化一遍。如果你并不想用某些实现类,它也被加载并实例化了,这就造成了浪费。获取某个实现类的方式不够灵活,只能通过Iterator形式获取,不能根据某个参数来获取对应的实现类。

        多个并发多线程使用ServiceLoader类的实例是不安全的。

ShardingSphere 中的SPI实战


ShardingSphereServiceLoader中利用register方法注册加载拓展接口实现类并保存到内存org.apache.shardingsphere.spi.ShardingSphereServiceLoader#SERVICES中。


Java SOP 可插拔 模块化 java插拔式设计架构_Java_05

 

Java SOP 可插拔 模块化 java插拔式设计架构_Java SOP 可插拔 模块化_06

利用分片算法的例子更细节描述加载过程:

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.infra.config.algorithm;

import org.apache.shardingsphere.spi.lifecycle.SPIPostProcessor;
import org.apache.shardingsphere.spi.type.typed.TypedSPI;

import java.util.Properties;

/**
 * ShardingSphere algorithm.
 */
public interface ShardingSphereAlgorithm extends TypedSPI, SPIPostProcessor {
    
    /**
     * Get properties.
     *
     * @return properties
     */
    Properties getProps();
}
package org.apache.shardingsphere.sharding.spi;

import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithm;

/**
 * Sharding algorithm.
 */
public interface ShardingAlgorithm extends ShardingSphereAlgorithm {
}
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmFactory;
import org.apache.shardingsphere.sharding.spi.ShardingAlgorithm;
import org.apache.shardingsphere.spi.ShardingSphereServiceLoader;
import org.apache.shardingsphere.spi.type.typed.TypedSPIRegistry;

/**
 * Sharding algorithm factory.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ShardingAlgorithmFactory {
    
    static {
        ShardingSphereServiceLoader.register(ShardingAlgorithm.class);
    }
    
    /**
     * Create new instance of sharding algorithm.
     * 
     * @param shardingAlgorithmConfig sharding algorithm configuration
     * @return created instance
     */
    public static ShardingAlgorithm newInstance(final ShardingSphereAlgorithmConfiguration shardingAlgorithmConfig) {
        return ShardingSphereAlgorithmFactory.createAlgorithm(shardingAlgorithmConfig, ShardingAlgorithm.class);
    }
    
    /**
     * Judge whether contains sharding algorithm.
     *
     * @param shardingAlgorithmType sharding algorithm type
     * @return contains sharding algorithm or not
     */
    public static boolean contains(final String shardingAlgorithmType) {
        return TypedSPIRegistry.findRegisteredService(ShardingAlgorithm.class, shardingAlgorithmType).isPresent();
    }
}

        举例如org.apache.shardingsphere.sharding.factory.ShardingAlgorithmFactory 通过静态代码块static {ShardingSphereServiceLoader.register(ShardingAlgorithm.class); } 调用”增强版的service loader:ShardingSphereServiceLoader 注册Register service方法加载ShardingAlgorithm相关的spi拓展类。