Java插件扩展机制之SPI的示例分析

发布时间:2021-07-27 13:52:35 作者:小新
来源:亿速云 阅读:187

这篇文章给大家分享的是有关Java插件扩展机制之SPI的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

什么是SPI

SPI ,全称为 Service Provider Interface,是一种服务发现机制。其为框架提供了一个对外可扩展的能力。

与 接口类-实现类 提供的RPC 方式有什么区别?

public interface AdOpFromApolloService {}
public class AdOpFromDbServiceImpl implements AdOpFromDbService {}

假设我们需要实现RPC,是怎么做的?

RPC会在对应的接口类AdOpFromApolloService新增一个注解用于标注是RPC类,然后将当前类放在依赖包提供给其他项目来通过接口类进行调用

简而言之:RPC调用中只提供接口类,然后让第三方调用(第三方只调,不写实现)

那RPC究竟跟SPI什么关系?

SPI的应用场景

框架实现案例:

  1. Spring扩展插件实现。如JDCB

  2. 中间件扩展插件实现。如Dubbo、Apollo

  3. 开发过程中举例:实现一个拦截器,并用SPI机制来扩展其拦截方式(比如全量拦截、每分钟拦截多少、拦截比例多少、拦截的日志是log打印还是落库、落es)

怎么实现一个SPI?

接下来用两个项目模块来讲解SPI的用法,先看项目结构图如下

Java插件扩展机制之SPI的示例分析

接下来是实现的过程

第一步:创建spi-demo-contract项目,在resources目录下新建如下目录(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService)


第二步:创建spi-demo项目,然后引入spi-demo-contract依赖


第三步:在spi-demo项目中用ServiceLoader进行加载SPI接口

补充说明:我们可以重写声明类的优先级,来判断需要用哪个实现类来处理。比如重写一个优先级=0最高优先级,然后加载的时候默认只取第一个优先级最高的,那我们重写的自定义实现类就能覆盖掉默认SPI实现类

详细步骤拆分如下

-- resources
---- META-INF
-------- services
------------ com.example.spidemocontract.spi.SpiTestDemoService
com.example.spidemocontract.spi.impl.DefaultSpiTestDemoService
/**
* 这个接口类完全对应resources/META-INF/services/com.example.spidemocontract.spi.impl.DefaultSpiTestDemoService
**/
public interface SpiTestDemoService {
    void printLog();
    int getOrder();
}

/**
 * 将默认的设置为优先级最低,这是默认的SPI接口的实现类
 */
public class DefaultSpiTestDemoService implements SpiTestDemoService {
    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }
    @Override
    public void printLog() {
        System.out.println("输出 DefaultSpiTestDemoService log");
    }
}
<dependency>
    <groupId>com.example</groupId>
    <artifactId>spi-demo-contract</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>
-- resources
---- META-INF
-------- services
------------ com.example.spidemocontract.spi.SpiTestDemoService
com.example.spidemo.spi.OtherSpiTestDemoService
/**
 * 其他,把他优先级设置的比较高
 */
public class OtherSpiTestDemoService implements SpiTestDemoService {
    // 后面我们用SPI类加载器获取时,会根据order排序,越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
    @Override
    public void printLog() {
        System.out.println("输出 OtherSpiTestDemoService log");
    }
}
public static void main(String[] args) {
    // 加载SPI
    Iterator<SpiTestDemoService> iterator = ServiceLoader.load(SpiTestDemoService.class).iterator();
    // 实现了ordered,会根据ordered返回值排序,优先级越高,越先取出来
    List<SpiTestDemoService> list = Lists.newArrayList(iterator)
            .stream().sorted(Comparator.comparing(SpiTestDemoService::getOrder))
            .collect(Collectors.toList());
    for (SpiTestDemoService item : list) {
        item.printLog();
    }
}

中间件是怎么实现SPI的?

Apollo-Client中的实现

// 当前接口会在resource/META-INF/services目录下对应文件com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper
public interface ConfigPropertySourcesProcessorHelper extends Ordered {
  void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
public class DefaultConfigPropertySourcesProcessorHelper implements ConfigPropertySourcesProcessorHelper {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // .....各种注册bean,初始化的流程
    }
    @Override
    public int getOrder() {
        // 优先级排序置为最低。方便其他自定义spi实现类能够覆盖
        return Ordered.LOWEST_PRECEDENCE;
    }
}

通过ServiceLoader.load(Xxxx.class)加载出所有实例,然后根据order来进行排序优先级,order最小的那个优先级最高,只取第一个数据candidates.get(0)并返回。
因为自定义SPI实现优先级可以设置得很高,所以就可以达到覆盖默认实现的目的

public static <S extends Ordered> S loadPrimary(Class<S> clazz) {
    List<S> candidates = loadAllOrdered(clazz);
    return candidates.get(0);
}
public static <S extends Ordered> List<S> loadAllOrdered(Class<S> clazz) {
    Iterator<S> iterator = loadAll(clazz);

    if (!iterator.hasNext()) {
      throw new IllegalStateException(String.format(
          "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
          clazz.getName()));
    }
    // 获取迭代中的所有SPI实现实例,然后进行排序,取优先级最高的那个
    List<S> candidates = Lists.newArrayList(iterator);
    Collections.sort(candidates, new Comparator<S>() {
      @Override
      public int compare(S o1, S o2) {
        // the smaller order has higher priority
        return Integer.compare(o1.getOrder(), o2.getOrder());
      }
    });

    return candidates;
}

JDBC中的实现

com.example.app.driver.MyDriver
public class MyDriver extends NonRegisteringDriver implements Driver {
    static {
        try {
            java.sql.DriverManager.registerDriver(new MyDriver());
        } catch (SQLException e) {
            throw new RuntimeException("Can't register driver!", e);
        }
    }
    public MyDriver() throws SQLException {}
    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        System.out.println("MyDriver - 准备创建数据库连接.url:" + url);
        System.out.println("JDBC配置信息:" + info);
        info.setProperty("user", "root");
        Connection connection = super.connect(url, info);
        System.out.println("MyDriver - 数据库连接创建完成!" + connection.toString());
        return connection;
    }
}
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String user = "root";
String password = "root";
Class.forName("com.example.app.driver.MyDriver");
Connection connection = DriverManager.getConnection(url, user, password);

获取所有注册的驱动(每个驱动的都遍历一下,其实就是最晚注册那个就用那个了,如果失败就往下一个找)

// 获取所有注册的驱动(每个驱动的都遍历一下,其实就是最晚注册那个就用那个了,如果失败就往下一个找)
 for(DriverInfo aDriver : registeredDrivers) {
    // If the caller does not have permission to load the driver then
    // skip it.
    if(isDriverAllowed(aDriver.driver, callerCL)) {
        try {
            println("    trying " + aDriver.driver.getClass().getName());
            Connection con = aDriver.driver.connect(url, info);
            if (con != null) {
                // Success!
                println("getConnection returning " + aDriver.driver.getClass().getName());
                return (con);
            }
        } catch (SQLException ex) {
            if (reason == null) {
                reason = ex;
            }
        }

    } else {
        println("    skipping: " + aDriver.getClass().getName());
    }
}

感谢各位的阅读!关于“Java插件扩展机制之SPI的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Java SPI机制原理是什么?
  2. Java中SPI 机制的原理是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java spi

上一篇:如何解决VSCode远程连接其他主机的WSL2的问题

下一篇:PHP如何使用Redis替代文件存储Session

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》