SPI机制

基本概述

SPI 全称 Service Provider Interface ,是一种服务发现机制。通过提供接口、预定义的加载器( Loader )以及约定俗称的配置(一般在 META-INF 目录下),可以实现动态加载服务实现类。

类图

通过类图可以分析出, ServiceLoader 实现了 Iterable 接口,提供了迭代的功能。

ServiceLoader 将迭代的实现委托给 LazyIterator

LazyIterator 提供了延时迭代的能力,当有需要的时候,才去加载。

Skywalking 模块中的使用

接口定义

org.apache.skywalking.oap.server.library.module.ModuleDefine

package org.apache.skywalking.oap.server.library.module;

import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ServiceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* A module definition.
*/
public abstract class ModuleDefine implements ModuleProviderHolder { private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDefine.class); private ModuleProvider loadedProvider = null; private final String name; public ModuleDefine(String name) {
this.name = name;
} /**
* @return the module name
*
*/
public final String name() {
return name;
} /**
* @return the {@link Service} provided by this module.
*/
public abstract Class[] services(); /**
* Run the prepare stage for the module, including finding all potential providers, and asking them to prepare.
*
* @param moduleManager of this module
* @param configuration of this module
* @throws ProviderNotFoundException when even don't find a single one providers.
*/
void prepare(ModuleManager moduleManager, ApplicationConfiguration.ModuleConfiguration configuration,
ServiceLoader<ModuleProvider> moduleProviderLoader) throws ProviderNotFoundException, ServiceNotProvidedException, ModuleConfigException, ModuleStartException {
// etc...
} // etc... @Override
public final ModuleProvider provider() throws DuplicateProviderException, ProviderNotFoundException {
if (loadedProvider == null) {
throw new ProviderNotFoundException("There is no module provider in " + this.name() + " module!");
}
return loadedProvider;
}
}

接口实现

org.apache.skywalking.oap.server.library.module.BaseModuleA

package org.apache.skywalking.oap.server.library.module;

public class BaseModuleA extends ModuleDefine {

    public BaseModuleA() {
super("BaseA");
} // 需要提供服务的接口
@Override
public Class<? extends Service>[] services() {
return new Class[] {
ServiceABusiness1.class,
ServiceABusiness2.class
};
} public interface ServiceABusiness1 extends Service {
void print();
} public interface ServiceABusiness2 extends Service {
}
}

META-INF 定义

META-INF/services/org.apache.skywalking.oap.server.library.module.ModuleDefine

org.apache.skywalking.oap.server.library.module.BaseModuleA

使用方式

org.apache.skywalking.oap.server.library.module.ModuleManager#init

    /**
* Init the given modules
*/
public void init(ApplicationConfiguration applicationConfiguration) /* etc... */ {
// SPI机制加载
ServiceLoaderModuleDefine> moduleServiceLoader = ServiceLoader.load(ModuleDefine.class);
// 迭代器获取
for (ModuleDefine module : moduleServiceLoader) {
// do something
// etc...
}
// etc...
}

源码解析

package java.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException; public final class ServiceLoader<S> implements Iterable<S> {
// 目录前缀
private static final String PREFIX = "META-INF/services/"; // 需要被加载对象的Class对象
private final Class<S> service; // 类加载器
private final ClassLoader loader; // The access control context taken when the ServiceLoader is created
private final AccessControlContext acc; // 加载对象缓存(按实例化顺序排序)
private LinkedHashMap<String,S> providers = new LinkedHashMap<>(); // 当前使用的懒加载迭代器
private LazyIterator lookupIterator; // 重载
public void reload() {
// 清除加载对象缓存
providers.clear();
// 重置懒加载迭代器
lookupIterator = new LazyIterator(service, loader);
} // 不允许直接创建ServiceLoader对象,只能通过loadXXX获取ServiceLoader对象
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();
} private static void fail(Class<?> service, String msg, Throwable cause) throws ServiceConfigurationError {
throw new ServiceConfigurationError(service.getName() + ": " + msg, cause);
} private static void fail(Class<?> service, String msg) throws ServiceConfigurationError {
throw new ServiceConfigurationError(service.getName() + ": " + msg);
} private static void fail(Class<?> service, URL u, int line, String msg) throws ServiceConfigurationError {
fail(service, u + ":" + line + ": " + msg);
} // 解析配置文件中的一行,如果没有注释,则加入到类名列表中
private int parseLine(Class<?> service, URL u, BufferedReader r, int lc, List<String> names) throws IOException, ServiceConfigurationError {
String ln = r.readLine();
if (ln == null) {
return -1;
}
int ci = ln.indexOf('#');
if (ci >= 0) ln = ln.substring(0, ci);
ln = ln.trim();
int n = ln.length();
if (n != 0) {
if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
fail(service, u, lc, "Illegal configuration-file syntax");
int cp = ln.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
fail(service, u, lc, "Illegal provider-class name: " + ln);
for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
cp = ln.codePointAt(i);
if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
fail(service, u, lc, "Illegal provider-class name: " + ln);
}
if (!providers.containsKey(ln) && !names.contains(ln))
names.add(ln);
}
return lc + 1;
} // 解析配置文件,返回实现类名列表
private Iterator<String> parse(Class<?> service, URL u) throws ServiceConfigurationError {
InputStream in = null;
BufferedReader r = null;
ArrayList<String> names = new ArrayList<>();
try {
in = u.openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8"));
int lc = 1;
while ((lc = parseLine(service, u, r, lc, names)) >= 0);
} catch (IOException x) {
fail(service, "Error reading configuration file", x);
} finally {
try {
if (r != null) r.close();
if (in != null) in.close();
} catch (IOException y) {
fail(service, "Error closing configuration file", y);
}
}
return names.iterator();
} // 懒加载迭代器,提供了延时迭代的能力,当有需要的时候,才去加载
private class LazyIterator implements Iterator<S> {
// 需要被加载对象的Class对象
Class<S> service;
// 类加载器
ClassLoader loader;
// 配置文件列表
Enumeration<URL> configs = null;
// 当前迭代的配置文件中类名列表的迭代器
Iterator<String> pending = null;
// 下一个实现类名
String nextName = null; private LazyIterator(Class<S> service, ClassLoader loader) {
this.service = service;
this.loader = loader;
} // 是否有下一个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;
} // 获取下一个Service
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 {
// 实例化
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
} // 迭代器,是否有下个元素
public boolean hasNext() {
if (acc == null) {
return hasNextService();
} else {
// 授权资源
PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
public Boolean run() { return hasNextService(); }
};
return AccessController.doPrivileged(action, acc);
}
} // 迭代器,获取下个元素
public S next() {
if (acc == null) {
return nextService();
} else {
// 授权资源
PrivilegedAction<S> action = new PrivilegedAction<S>() {
public S run() { return nextService(); }
};
return AccessController.doPrivileged(action, acc);
}
} // 不支持删除
public void remove() {
throw new UnsupportedOperationException();
} } // 迭代器实现,如果有缓存从缓存中获取,没有则从懒加载迭代器加载
public Iterator<S> iterator() {
return new Iterator<S>() {
Iterator<Map.Entry<String,S>> knownProviders = providers.entrySet().iterator(); public boolean hasNext() {
if (knownProviders.hasNext())
return true;
return lookupIterator.hasNext();
} public S next() {
if (knownProviders.hasNext())
return knownProviders.next().getValue();
return lookupIterator.next();
} public void remove() {
throw new UnsupportedOperationException();
}
};
} // 通过类的Class对象及类加载,获取ServiceLoader
public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader) {
return new ServiceLoader<>(service, loader);
} // 通过类的Class对象,获取ServiceLoader
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
} // 通过类的Class对象和扩展类加载器,获取ServiceLoader
public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
ClassLoader prev = null;
while (cl != null) {
prev = cl;
cl = cl.getParent();
}
return ServiceLoader.load(service, prev);
} public String toString() {
return "java.util.ServiceLoader[" + service.getName() + "]";
} }

PS: JDK 提供的 SPI 机制,必须要使用迭代器遍历获取需要的实现,而 Dubbo SPI 可以通过 #getExtension 获取指定实现类。

总结

通过源码分析,可以了解到 Skywalking 没有定义自己的 SPI 机制,但深入阅读 Skywalking 的使用场景后,发现用 JDK 提供的 SPI 机制也没什么问题。

个人认为,任何技术都应该根据场景选取,适合的才是最好的,如果没有那么复杂的需要,没必要像 dubbo 一样,定义自己的 SPI 机制。

参考文档

分享并记录所学所见

Skywalking-12:Skywalking SPI机制的更多相关文章

  1. Skywalking-13:Skywalking模块加载机制

    模块加载机制 基本概述 Module 是 Skywalking 在 OAP 提供的一种管理功能特性的机制.通过 Module 机制,可以方便的定义模块,并且可以提供多种实现,在配置文件中任意选择实现. ...

  2. Java SPI机制简介

    SPI 简介 SPI 全称为 (Service Provider Interface) ,是JDK内置的一种服务提供发现机制. 目前有不少框架用它来做服务的扩展发现, 简单来说,它就是一种动态替换发现 ...

  3. JDK源码系列(一) ------ 深入理解SPI机制

    什么是SPI机制 最近我建了另一个文章分类,用于扩展JDK中一些重要但不常用的功能. SPI,全名Service Provider Interface,是一种服务发现机制.它可以看成是一种针对接口实现 ...

  4. Java的SPI机制

    目录 1. 什么是SPI 2. 为什么要使用SPI 3. 关于策略模式和SPI的几点区别 4. 使用介绍或者说约定 4.1 首先介绍几个名词 4.2 约定 5. 具体的demo实现 5.1 创建服务提 ...

  5. 利用SPI机制实现责任链模式中的处理类热插拔

    最近看到责任链模式的时候每增加一个处理类,就必须在责任链的实现类中手动增加到责任链中,具体代码基本就是list.add(new FilterImpl()),可以看到每次增加一个处理类,就必须添加一行上 ...

  6. 一文搞懂Java/Spring/Dubbo框架中的SPI机制

    几天前和一位前辈聊起了Spring技术,大佬突然说了SPI,作为一个熟练使用Spring的民工,心中一紧,咱也不敢说不懂,而是在聊完之后赶紧打开了浏览器,开始的学习之路,所以也就有了这篇文章.废话不多 ...

  7. Java SPI机制,你了解过吗?

    Life moves pretty fast,if you don't stop and look around once in a while,you will miss it 为什么需要SPI? ...

  8. java中的SPI机制

    1 SPI机制简介 SPI的全名为Service Provider Interface.大多数开发人员可能不熟悉,因为这个是针对厂商或者插件的.在java.util.ServiceLoader的文档里 ...

  9. java 的SPI机制

    今天看到spring mvc 使用Java Validation Api(JSR-303)进行校验,需要加载一个 其具体实现(比如Hibernate Validator), 本来没有什么问题,但是突然 ...

随机推荐

  1. windows编译boost

    1. https://www.boost.org 下载boost源码 boost_1_73_0.zip解压. 2.准备编译前的配置,打开vs2017 x86 CMD工具,进入目录boost_1_73_ ...

  2. POI实现excel的导入导出

    引入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</arti ...

  3. 细说Typescript类型检查机制

    上一篇文章我介绍了Typescript的基础知识,回顾一下,有基础数据类型.数组.函数.类.接口.泛型等,本节内容将述说一下Typescript为方便我们开发提供了一些类型检查机制. 类型检查机制 类 ...

  4. 并发编程之:Atomic

    大家好,我是小黑,一个在互联网苟且偷生的农民工. 在开始讲今天的内容之前,先问一个问题,使用int类型做加减操作是不是线程安全的呢?比如 i++ ,++i,i=i+1这样的操作在并发情况下是否会有问题 ...

  5. C# - 音乐小闹钟_BetaV3.0

    时间:2017-11-22 作者:byzqy 介绍: 音乐小闹钟 BetaV3.0 新鲜出炉了,快来围观吧!上效果图: 是不是觉得顿时变得高大上了许多呢?^_^ 工具/原料: (操作系统:Window ...

  6. MySQL中的seconds_behind_master的理解

    通过show slave status查看到的Seconds_Behind_Master,从字面上来看,他是slave落后master的秒数,一般情况下,也确实这样,我们可以通过Seconds_Beh ...

  7. Springboot 日志、配置文件、接口数据如何脱敏?老鸟们都是这样玩的!

    一.前言 核心隐私数据无论对于企业还是用户来说尤其重要,因此要想办法杜绝各种隐私数据的泄漏.下面陈某带大家从以下三个方面讲解一下隐私数据如何脱敏,也是日常开发中需要注意的: 配置文件数据脱敏 接口返回 ...

  8. group by分组查询

    有如下数据: 一个简单的分组查询的案例 按照部门编号deptno分组,统计每个部门的平均工资. select deptno,avg(sal) avgs from emp group by deptno ...

  9. Linux常用命令(一)之文件处理命令

    分时的多用户.多任务的操作系统 多数的网络协议的支持(unix和tcp/ip协议是同时发展起来的),方便的远程管理(可以通过图形.命令行) 强大的内存管理和文件管理系统 大量的可用软件和免费软件(游戏 ...

  10. Kafka详细教程加面试题

    一.部署kafka集群 启动zookeeper服务: zkServer.sh start 修改配置文件config/server.properties #broker 的全局唯一编号,不能重复 bro ...