SPI机制源码:JDK Dubbo Spring

news2024/9/25 19:15:43

JDK 17
Dubbo 3.1.6

JDK SPI

JDK SPI在sql驱动类加载、以及slf4j日志实现加载方面有具体实现。

示例

在这里插入图片描述

public class Test {
    private static final Logger logger = LoggerFactory.getLogger(Test.class);

    public static void main(String[] args) {

        ServiceLoader<JdkSpiService> services = ServiceLoader.load(JdkSpiService.class);

        Set<JdkSpiService> jdkSpiServices = services.stream().map(ServiceLoader.Provider::get).collect(Collectors.toSet());

//        for (JdkSpiService service : services) {
//            logger.info(service.test());
//        }
    }
}

ServiceLoader

由ServiceLoader提供,该类实现了Iterable接口,懒加载SPI实现类,所以加载逻辑都封装在内部迭代器类LazyClassPathLookupIterator implements Iterator里,当迭代器迭代时,会调用#hasNext,此时会调用#hasNextService 该方法又会调用#nextProviderClass加载SPI类:


public final class ServiceLoader<S>
    implements Iterable<S>
{
	    private final class LazyClassPathLookupIterator<T>
        implements Iterator<Provider<T>>
    {
        static final String PREFIX = "META-INF/services/";
        // 将相对路径变为绝对路径存储,存储多个SPI接口文件
		Enumeration<URL> configs;
		// 每个SPI文件中的实现类全类名
		Iterator<String> pending;

		
		/**
         * Loads and returns the next provider class.
         */
        private Class<?> nextProviderClass() {
        	// 首次获取spi实现类,会先从META-INF/services/接口全类名中读取所有的记录到configs中
            if (configs == null) {
                try {
                	// 相对路径名 Reference Path
                    String fullName = PREFIX + service.getName();
                    // ********************************************************
                    // 需要通过类加载器加载资源,下面根据类加载器类型加载fullName资源
                    // ********************************************************
						
                    if (loader == null) {
                        configs = ClassLoader.getSystemResources(fullName);
                    } else if (loader == ClassLoaders.platformClassLoader()) {
                       ...
                    } else {
                    	// 一般走这里
                    	// 一般为线程上下文类加载器
                        configs = loader.getResources(fullName);
                    }
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            // 第一次为null进入,或者已经执行完毕没有了再进入
            // 迭代同一个接口文件中的内容时,该while不会进入
            while ((pending == null) || !pending.hasNext()) {
                if (!configs.hasMoreElements()) {
                    return null;
                }
                // 解析一个接口文件中所有的实现类全类名
               	// URLConnection uc = URL#openConnection;
               	// InputStream in = uc.getInputStream();
                // BufferedReader r = new BufferedReader(new InputStreamReader(in, UTF_8.INSTANCE))
                pending = parse(configs.nextElement());
            }
            // 下一个实现类名
            String cn = pending.next();
            try {
            	// 反射实现类加载
                return Class.forName(cn, false, loader);
            } catch (ClassNotFoundException x) {
                fail(service, "Provider " + cn + " not found");
                return null;
            }
        }
	}
	
}

关于sql的SPI中使用了AccessController#doPrivileged,可以参考AccessController usage。简单来说,就是在SecurityManger中指定了某个jar包的security policy,当该jar包中的方法a调用如System.getProperty()方法时,如果没有包裹doPrivileged,会检查方法a调用栈中所有方法是否都被授予权限。而包裹了doPrivileged,只会检查当前方法a的权限。
不过该AccessControllerSecurityManager在 Java 17后即将被移除,且无替代。参见 Class AccessController,关于为什么移除,参见 JEP 411: Deprecate the Security Manager for Removal,简单来说就是SecurityManager解决的两个问题已经不是问题,但是维护它却很费力且性能低。

Dubbo SPI

示例

Dubbo SPI 导入格式:

在这里插入图片描述

public class Test {
    public static void main(String[] args) {
		// 这里的几个方法都会检查传入的是否是接口以及是否标注@SPI
        ExtensionLoader<DubboSpiTest> extensionLoader = 
        					ApplicationModel.defaultModel()
        					.getExtensionDirector()
        					.getExtensionLoader(DubboSpiTest.class);
		
        DubboSpiTest test1 = extensionLoader.getExtension("test1");
        DubboSpiTest test2 = extensionLoader.getExtension("test2");
    }
}

JDK SPI对应了一个ServiceLoader类,同样Dubbo SPI对应了一个ExtensionLoader。

LoadingStategy

先看该接口。Dubbo SPI 从META-INF下哪个文件夹加载,加载优先级如何,key同名是否支持覆盖等策略信息均由LoadingStrategy接口提供。

LoadingStrategy代表spi加载策略,该接口提供基本的加载信息,默认3个实现类:

  • DubboInternalLoadingStrategy : 内部加载策略,key同名不可覆盖
  • DubboLoadingStrategy:key同名可覆盖
  • ServicesLoadingStrategy:key同名可覆盖

3个实现类的初始化方式是通过JDK SPI机制引入,参考ExtensionLoader类:

public class ExtensionLoader<T> {
	...
	private static volatile LoadingStrategy[] strategies = loadLoadingStrategies();
	...
	// Spliterator接口
	private static LoadingStrategy[] loadLoadingStrategies() {
        return stream(load(LoadingStrategy.class).spliterator(), false)
            .sorted()
            .toArray(LoadingStrategy[]::new);
    }	
	...
	// 获取LoadingStrategy
	public static List<LoadingStrategy> getLoadingStrategies() {
        return asList(strategies);
    }
}

ExtensionLoader

新版本中,ExtensionLoader#getExtensionLoaderExtensionFactory接口都已被废弃,改进如下:

  • ExtensionLoader#getExtensionLoader → \rightarrow ExtensionDirector#getExtensionLoader
  • ExtensionFactory → \rightarrow ExtensionInjector,其实现类由 AdaptiveExtensionFactory → \rightarrow AdaptiveExtensionInjector,Adaptive是一个门面,具体干活的由 SpiExtensionFactory → \rightarrow SpiExtensionInjector,但是所有干活的逻辑弯弯绕绕后又回到ExtensionLoader中,很奇怪。

最终由 ExtensionLoader#loadExtensionClasses执行代码:

public class ExtensionLoader<T> {
	...
	private static volatile LoadingStrategy[] strategies = loadLoadingStrategies();
	...
	private Map<String, Class<?>> loadExtensionClasses() throws InterruptedException {
        checkDestroyed();
        cacheDefaultExtensionName();

        Map<String, Class<?>> extensionClasses = new HashMap<>();

        for (LoadingStrategy strategy : strategies) {
            loadDirectory(extensionClasses, strategy, type.getName());

            // compatible with old ExtensionFactory
            if (this.type == ExtensionInjector.class) {
                loadDirectory(extensionClasses, strategy, ExtensionFactory.class.getName());
            }
        }

        return extensionClasses;
    }
	
	private void loadDirectory(Map<String, Class<?>> extensionClasses, LoadingStrategy strategy, String type) throws InterruptedException {
        loadDirectoryInternal(extensionClasses, strategy, type);
       	...
    }
	
	private void loadDirectoryInternal(Map<String, Class<?>> extensionClasses, LoadingStrategy loadingStrategy, String type) throws InterruptedException {
		
		String fileName = loadingStrategy.directory() + type;

		// 可用的classLoader集合
		List<ClassLoader> classLoadersToLoad = new LinkedList<>();
		
		// 先加入ExtensionLoader的类加载器
        if (loadingStrategy.preferExtensionClassLoader()) {
                ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader();
                // 不能是系统类加载器
                if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) {
                    classLoadersToLoad.add(extensionLoaderClassLoader);
                }
            }
		
		// 获取classloader
		Set<ClassLoader> classLoaders = scopeModel.getClassLoaders();
		
		// 如果classloader为空,则用系统类加载器加载SPI文件
		if (CollectionUtils.isEmpty(classLoaders)) {
			Enumeration<java.net.URL> resources = ClassLoader.getSystemResources(fileName);
		
		}
		// 否则加入classLoader集合
		else {
			classLoadersToLoad.addAll(classLoaders);
		}
		
		// 工具类 多个classLoadersToLoad并行搜寻各个classLoader来加载资源
		// 但是基本只有一个classLoader,不知道为啥这么设计
		Map<ClassLoader, Set<java.net.URL>> resources = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad);
		// 遍历所有,反射生成SPI实现类并加入到extensionClasses集合中
		resources.forEach(((classLoader, urls) -> {
                loadFromClass(extensionClasses,...);
            }));
	}

	
}

Spring SPI

注意,该SPI机制属于 org.springframework.core包下,通常用在自定义spring-boot-starter中。

示例

在这里插入图片描述

public class TestSpringSpiApplication  {

    public static void main(String[] args) {

        List<TestSpringSpi> spiList = SpringFactoriesLoader.loadFactories(TestSpringSpi.class, Thread.currentThread().getContextClassLoader());

        for (TestSpringSpi spi : spiList) {
            spi.test();
        }
    }
}

SpringFactoriesLoader

public final class SpringFactoriesLoader {
	
	public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
	// 缓存
	static final Map<ClassLoader, Map<String, List<String>>> cache = new ConcurrentReferenceHashMap<>();
	...


	public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
		Assert.notNull(factoryType, "'factoryType' must not be null");
		ClassLoader classLoaderToUse = classLoader;
		//classloader未指定就用该类的classloader
		if (classLoaderToUse == null) {
			classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
		}
		// 加载spi实现类的全类名
		List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
		
		List<T> result = new ArrayList<>(factoryImplementationNames.size());
		
		for (String factoryImplementationName : factoryImplementationNames) {
			result.add(
				// 反射类加载
				instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse)
			);
		}
		AnnotationAwareOrderComparator.sort(result);
		return result;
	}
	// 加载名称,这里主要做前置检查和结果处理
	public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
		... // 进一步检查
		// 加载所有的spring.factories中内容,并获取,没有就返回空列表
		return loadSpringFactories(classLoaderToUse)
					.getOrDefault(factoryTypeName, Collections.emptyList());
	}
	
	private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
		// 先从缓存中获取所有加载的springfactories中内容
		Map<String, List<String>> result = cache.get(classLoader);
		if (result != null) {
			return result;
		}
		// 初始化加载
		result = new HashMap<>();
		try {
			// 获取到MEAT-INF/spring.factories文件的URL,通常就一个
			Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				UrlResource resource = new UrlResource(url);
				// 加载所有的key=value
				Properties properties = PropertiesLoaderUtils.loadProperties(resource);
				for (Map.Entry<?, ?> entry : properties.entrySet()) {
						...
				}
			}

			// Replace all lists with unmodifiable lists containing unique elements
			result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
					.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
			// 加入缓存
			cache.put(classLoader, result);
		}
		catch (IOException ex) {
			...
		}
		return result;
	}
}

总结

不管是哪一类,基本结构步骤就是

  1. 获取类加载器
  2. 利用类加载器在固定路径加载SPI文件,ClassLoader#getResources生成Enumeration<java.net.URL>对象(通常只有一个URL
  3. 对URL对象实施解析,获取实现类全类名
  4. 反射实施类加载 Class#forName → \rightarrow Constructor#newInstance

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/367102.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

软件测试计划怎么写?模板在这呢

目录 第1章 引言 第2章 项目背景 第3章质量目标 第4章 资源需求 第5章 测试策略 第6章 测试计划 总结感谢每一个认真阅读我文章的人&#xff01;&#xff01;&#xff01; 重点&#xff1a;配套学习资料和视频教学 第1章 引言 1.1目的 简述本计划的目的&#xff0c;旨…

【THREE.JS学习(3)】使用THREEJS加载GeoJSON地图数据

本文接着系列文章&#xff08;2&#xff09;进行介绍&#xff0c;以VUE2为开发框架&#xff0c;该文涉及代码存放在HelloWorld.vue中。相较于上一篇文章对div命名class等&#xff0c;该文简洁许多。<template> <div></div> </template>接着引入核心库i…

RPC(3)--基于 Nacos 的服务发现与负载均衡版

nacos:提供了一组简单易用的特性集&#xff0c;帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。 nacos架构如下(图片来源) 依赖包&#xff1a; <dependency>…

国内领先的十大API接口排行

应用程序编程接口API即&#xff08;Application Programming Interface&#xff09;&#xff0c;现在众多企业的应用系统中常用的开放接口&#xff0c;对接相应的系统、软件功能&#xff0c;简化专业化的程序开发。 一、百度API 百度API超市开通1136个数据服务接口。 网址&a…

git 的使用方法 (下 - 远程仓库和图形化)

目录前言&#xff1a;一、什么是协同开发二、Gitee 使用协同开发1. 首先注册一个码云账号2. 新建一个仓库3. 根据下图把新建仓库设置为开源4. 在远端合并分支的方法5. 链接 git 远程6. 提交&#xff08;同步&#xff09;远程7. 远程拉取至本地8. 远程分支三、git 图形化的使用1…

ROS2手写接收IMU数据(Imu)代码并发布

目录前言接收IMU数据IMU的串口连接问题python接收串口数据python解析数据ROS2发布IMU数据可视化IMU数据效果前言 在前面测试完了单独用激光雷达建图之后&#xff0c;一直想把IMU的数据融合进去&#xff0c;由于经费的限制&#xff0c;忍痛在淘宝上买了一款便宜的IMU—GY95T&am…

实验室设计|兽医实验室设计|SICOLAB

新建兽医实验室时&#xff0c;需要考虑以下几个方面&#xff1a;&#xff08;1&#xff09;实验室建筑设计&#xff1a;实验室建筑设计应充分考虑实验室的功能需求&#xff0c;例如安全、通风、排水、电力等方面的设计&#xff0c;确保实验室内部环境的稳定和安全。&#xff08…

XX项目自动化测试方案模板,你学会了吗?

目录 1、引言 2、自动化实施目标 3、自动化技术选型 4、测试环境需求 5、人员进度安排 总结感谢每一个认真阅读我文章的人&#xff01;&#xff01;&#xff01; 重点&#xff1a;配套学习资料和视频教学 1、引言 文档版本 版本 作者 审批 备注 V1.0 Vincent XXX …

selenium环境安装及使用

selenium简介官网https://www.selenium.dev简介用于web浏览器测试的工具支持的浏览器包括IE&#xff0c;Firefox,Chrome&#xff0c;edge等使用简单&#xff0c;可使用java&#xff0c;python等多种语言编写用例脚本主要由三个工具构成&#xff0c;webdriver,IDE,web自动化环境…

【深度学习】优化器

1.什么是优化器 优化器是在深度学习的反向传播过程中&#xff0c;指引损失函数&#xff08;目标函数&#xff09;的各个参数往正确的方向更新合适的大小&#xff0c;使得更新后的各个参数让目标函数不断逼近全局最小点。 2.优化器 2-1 BGD 批量梯度下降法&#xff0c;是梯度下…

【阿旭机器学习实战】【33】中文文本分类之情感分析--朴素贝叶斯、KNN、逻辑回归

【阿旭机器学习实战】系列文章主要介绍机器学习的各种算法模型及其实战案例&#xff0c;欢迎点赞&#xff0c;关注共同学习交流。 目录1.查看原始数据结构2.导入数据并进行数据处理2.1 提取数据与标签2.2 过滤停用词2.3 TfidfVectorizer将文本向量化3.利用不同模型进行训练与评…

如何使用HTTPS加密保护网站?

加密 Web 内容并不是什么新鲜事&#xff1a;自发布通过SSL/TLS协议来加密 Web 内容的规范以来&#xff0c;已经过去了近 20 年。然而&#xff0c;近年来&#xff0c;运行安全的HTTPS加密 Web 服务器已经从一种选择变成了一种安全防护的必需品。攻击者继续寻找并找到窃取用户和W…

计算机网络概述 第二部分

5.网络分层 ①OSI 7层模型 数据链路层 (Data Link Layer) 实现相邻&#xff08;Neighboring&#xff09;网络实体间的数据传输 成帧&#xff08;Framing&#xff09;&#xff1a;从物理层的比特流中提取出完整的帧 错误检测与纠正&#xff1a;为提供可靠数据通信提供可能 …

算法笔记(十三)—— 树形DP及Morris遍历

树形DP&#xff1a; Question1: 以X为头结点的树&#xff0c;最大距离&#xff1a; 1. X不参与&#xff0c;在左子树上的最大距离 2. X不参与&#xff0c;在右子树上的最大距离 3. X参与&#xff0c;左树上最远的结点通过X到右树最远的结点 最后的结果一定是三种情况的最大…

【微信小程序】-- 常用视图容器类组件介绍(六)

&#x1f48c; 所属专栏&#xff1a;【微信小程序开发教程】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &#…

Spring Boot与Vue:实现图片的上传

文章目录1. 项目场景2. 问题描述3. 实现方案3.1 方案一&#xff1a;上传图片&#xff0c;转换成 Base64 编码并返回3.1.1 前端页面组件3.1.2 前端 JS 函数3.1.3 后端 Controller3.2 方案二&#xff1a;上传图片&#xff0c;并返回图片路径3.2.1 前端页面组件3.2.1 前端 JS 函数…

shell的函数

一、shell函数 有些脚本段间互相重复&#xff0c;如果能只写一次代码块而在任何地方都能引用那就提高了代码的可重用性。 shell 允许将一组命令集或语句形成一个可用块&#xff0c;这些块称为 shell 函数。 二、shell函数的格式 2.1.第一种格式 函数名&#xff08…

selenium自动化测试用例需要关注的几点

自动化测试设计简介注&#xff1a;参看文章地址 我们在本章提供的信息&#xff0c;对自动化测试领域的新人和经验丰富的老手都是有用的。本篇中描述最常见的自动化测试类型&#xff0c; 还描述了可以增强您的自动化测试套件可维护性和扩展性的“设计模式”。还没有使用这些技术…

Clion安装Platformio支持

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录前言一、系统配置二、什么是platformio三、安装配置1.安装Clion2.安装platformio插件3.安装platformio&#xff08;CLI&#xff09;4. 配置Clion环境5. 创建示例Demo…

低功耗设计:rush current

在power gating的设计中有一个rush current的概念&#xff0c;它的产生原因是switch cell上电过程相当于电容充电过程&#xff0c;会产生一个短期的大电流&#xff0c;称之为rush current。 1.rush current的危害 1&#xff09;rush current产生的压降可能会造成大的短路电流…