前言:
SPI是jdk內置的服務發現機制, 全稱叫Service Provider Interface.
SPI的工作原理, 就是ClassPath路徑下的META-INF/services文件夾中, 以接口的全限定名來命名文件名, 文件里面寫該接口的實現。 然后再資源加載的方式,讀取文件的內容(接口實現的全限定名), 然后再去加載類。
SPI可以很靈活的讓接口和實現分離, 讓api提供者只提供接口, 第三方來實現。
這一機制為很多框架的擴展提供了可能,比如在 Dubbo、JDBC、SpringBoot 中都使用到了SPI機制。雖然他們之間的實現方式不同,但原理都差不多。今天我們就來看看,SPI到底是何方神聖,在眾多開源框架中又扮演了什么角色。
一、JDK中的SPI
我們先從JDK開始,通過一個很簡單的例子來看下它是怎么用的。
1、小栗子
首先,我們需要定義一個接口,SpiService
package com.dxz.jdk.spi; public interface SpiService { void println(); }
然后,定義一個實現類,沒別的意思,只做打印。
package com.dxz.jdk.spi; public class SpiServiceImpl implements SpiService { @Override public void println() { System.out.println("------SPI DEMO-------"); } }
最后呢,要在resources路徑下配置添加一個文件。文件名字是接口的全限定類名,內容是實現類的全限定類名,多個實現類用換行符分隔。
文件內容就是實現類的全限定類名:
2、測試
然后我們就可以通過 ServiceLoader.load 方法拿到實現類的實例,並調用它的方法。
public static void main(String[] args){ ServiceLoader<SpiService> load = ServiceLoader.load(SpiService.class); Iterator<SpiService> iterator = load.iterator(); while (iterator.hasNext()){ SpiService service = iterator.next(); service.println(); } }
3、源碼分析
首先,我們先來了解下 ServiceLoader,看看它的類結構。
public final class ServiceLoader<S> implements Iterable<S>{ //配置文件的路徑 private static final String PREFIX = "META-INF/services/"; //加載的服務類或接口 private final Class<S> service; //已加載的服務類集合 private LinkedHashMap<String,S> providers = new LinkedHashMap<>(); //類加載器 private final ClassLoader loader; //內部類,真正加載服務類 private LazyIterator lookupIterator; }
當我們調用 load 方法時,並沒有真正的去加載和查找服務類。而是調用了 ServiceLoader 的構造方法,在這里最重要的是實例化了內部類 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; //先清空 providers.clear(); //實例化內部類 LazyIterator lookupIterator = new LazyIterator(service, loader); }
查找實現類和創建實現類的過程,都在 LazyIterator 完成。當我們調用 iterator.hasNext和iterator.next 方法的時候,實際上調用的都是 LazyIterator 的相應方法。
public Iterator<S> iterator() { return new Iterator<S>() { public boolean hasNext() { return lookupIterator.hasNext(); } public S next() { return lookupIterator.next(); } ....... }; }
所以,我們重點關注 lookupIterator.hasNext() 方法,它最終會調用到 hasNextServicez ,在這里返回實現類名稱。
private class LazyIterator implements Iterator<S>{ Class<S> service; ClassLoader loader; Enumeration<URL> configs = null; Iterator<String> pending = null; String nextName = null; private boolean hasNextService() { //第二次調用的時候,已經解析完成了,直接返回 if (nextName != null) { return true; } if (configs == null) { //META-INF/services/ 加上接口的全限定類名,就是文件服務類的文件 //META-INF/services/com.viewscenes.netsupervisor.spi.SPIService String fullName = PREFIX + service.getName(); //將文件路徑轉成URL對象 configs = loader.getResources(fullName); } while ((pending == null) || !pending.hasNext()) { //解析URL文件對象,讀取內容,最后返回 pending = parse(service, configs.nextElement()); } //拿到第一個實現類的類名 nextName = pending.next(); return true; } }
然后當我們調用 next() 方法的時候,調用到 lookupIterator.nextService 。它通過反射的方式,創建實現類的實例並返回。
private S nextService() { //全限定類名 String cn = nextName; nextName = null; //創建類的Class對象 Class<?> c = Class.forName(cn, false, loader); //通過newInstance實例化 S p = service.cast(c.newInstance()); //放入集合,返回實例 providers.put(cn, p); return p; }
到這為止,已經獲取到了類的實例。
二、JDBC中的應用
我們開頭說,SPI機制為很多框架的擴展提供了可能,其實JDBC就應用到了這一機制。
在以前,需要先設置數據庫驅動的連接,再通過 DriverManager.getConnection 獲取一個 Connection 。
String url = "jdbc:mysql:///consult?serverTimezone=UTC"; String user = "root"; String password = "root"; Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, user, password);
而現在,設置數據庫驅動連接,這一步驟就不再需要,那么它是怎么分辨是哪種數據庫的呢?答案就在SPI。
1、加載
下圖mysql Driver的實例。 com.mysql.cj.jdbc.Driver就是Driver的實現。
mysql驅動為例
mysql Driver實現類
Driver接口上的一段注釋。
DriverManager將嘗試加載盡可能多的驅動程序。
我們把目光回到 DriverManager 類,它在靜態代碼塊里面做了一件比較重要的事。很明顯,它已經通過SPI機制, 把數據庫驅動連接初始化了。
public class DriverManager { static { loadInitialDrivers(); println("JDBC DriverManager initialized"); } }
接下來我們去DriverManger上看看是如何加載Driver接口的實現類的。
public class DriverManager { /** * Load the initial JDBC drivers by checking the System property * jdbc.properties and then use the {@code ServiceLoader} mechanism */ static { loadInitialDrivers(); println("JDBC DriverManager initialized"); } private static void loadInitialDrivers() { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator<Driver> driversIterator = loadedDrivers.iterator(); try{ while(driversIterator.hasNext()) { driversIterator.next(); } } catch(Throwable t) { } return null; } }); }
在DriverManger類初始化的時候, 調用loadInitialDrivers方法。
具體過程還得看 loadInitialDrivers ,它在里面查找的是Driver接口的服務類,所以它的文件路徑就是:
META-INF/services/java.sql.Driver
在loadInitialDrivers方法中,
private static void loadInitialDrivers() { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { //很明顯,它要加載Driver接口的服務類,Driver接口的包為:java.sql.Driver //所以它要找的就是META-INF/services/java.sql.Driver文件 ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator<Driver> driversIterator = loadedDrivers.iterator(); try{ //查到之后創建對象 while(driversIterator.hasNext()) { driversIterator.next();//當調用next方法時,就會創建這個類的實例。它就完成了一件事,向 DriverManager 注冊自身的實例。 } } catch(Throwable t) { // Do nothing } return null; } }); }
這段代碼是實現SPI的關鍵, 真是這個ServiceLoader類去實現SPI的。 那么下面就分析分析ServiceLoader的代碼, 看看是如何實現SPI的。
package java.util; public final class ServiceLoader<S> implements Iterable<S> { public static <S> ServiceLoader<S> load(Class<S> service) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return ServiceLoader.load(service, cl); } //其中service就是要加載實現類對應的接口, loader就是用該加載器去加載對應的實現類 public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader){ return new ServiceLoader<>(service, loader); } }
先調用ServiceLoader類的靜態方法load, 然后根據當前線程的上下文類加載器,創建一個ServiceLoader實例。 關於類加載器,上篇文章剛分析完。
private static final String PREFIX = "META-INF/services/"; public void reload() { providers.clear(); lookupIterator = new LazyIterator(service, loader); } 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(); }
創建ServiceLoader實例的時候,接着創建一個Iterator實現類。 接下來這個Iterator分析的重點。基本所有的加載類的實現邏輯都在里面。
其中ServiceLoader類中一個常量的定義是關鍵的。 前面說過,我們service的實現類在放在哪, 就是這里寫死的常量路徑。
//這里先介紹Iterator的變量,先大概有個印象。 private class LazyIterator implements Iterator<S> { //service, loader前面介紹過了。 Class<S> service; ClassLoader loader; Enumeration<URL> configs = null; Iterator<String> pending = null; String nextName = null; public boolean hasNext() { //省略權限相關代碼 return hasNextService(); } private boolean hasNextService() { //一開始nextName肯定為空 if (nextName != null) { return true; } //一開始configs也肯定為空 if (configs == null) { try { //PREFIX = META-INF/services/ //以mysql為例,就是 META-INF/services/java.sql.Driver String fullName = PREFIX + service.getName(); if (loader == null) configs = ClassLoader.getSystemResources(fullName); //loader去加載這個classpath下文件。 //這里很有可能返回的是多個文件的資源, //例如一個項目下既有mysql驅動, 也有sql server驅動等 //所以返回的是一個枚舉類型。 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; } //然后根據加載出來的資源,解析一個文件中的內容。放到Iterator實現類中 pending = parse(service, configs.nextElement()); } //這里next返回的就是文件一行的內容,一般一行對應一個接口的實現類。 //一個接口放多行,就可以有多個接口實現類中。 nextName = pending.next(); return true; } }
configs變量,就對應service文件。 是個枚舉, 就是說可以定義多個service文件。
pending 變量: 就對應configs中, service文件解析出來的一行有效內容,即一個實現類的全限定類名稱。
parse方法就是簡單,不是重點。這里就略過了。就是讀取service文件中讀取,一行就是一個nextName,然后遇到“#“就跳過“#”后面的內容。所以service文件可以用“#”作為注釋。 直到遇到空行,解析結束。
LazyIterator類中的hasNext方法就分析完了。 使用classLoader.getResources方法加載service文件。我看了下getResources方法,並一定是加載classpath下的資源,得根據classLoader來解決。不過絕大多數情況下,都是classpath的資源。這里為了好理解,就理解成classpath下的資源。
接着分析LazyIterator#next方法。
public S next() { //刪除權限相關代碼 return nextService(); } private S nextService() { if (!hasNextService()) throw new NoSuchElementException(); //這個nextName前面分析過了 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()); //最后放到ServiceLoader實例變量Map中,緩存起來,下次直接使用 providers.put(cn, p); return p; } catch (Throwable x) { fail(service, "Provider " + cn + " could not be instantiated", x); } throw new Error(); // This cannot happen }
next方法就比較簡單了,根據前面解析出來的nextName(接口實現類的全限定名稱),用Class.forName創建對應的Class對象。
3、創建Connection
DriverManager.getConnection() 方法就是創建連接的地方,它通過循環已注冊的數據庫驅動程序,調用其connect方法,獲取連接並返回。
private static Connection getConnection(String url, Properties info, Class<?> caller) throws SQLException { //registeredDrivers中就包含com.mysql.cj.jdbc.Driver實例 for(DriverInfo aDriver : registeredDrivers) { if(isDriverAllowed(aDriver.driver, callerCL)) { try { //調用connect方法創建連接 Connection con = aDriver.driver.connect(url, info); if (con != null) { return (con); } }catch (SQLException ex) { if (reason == null) { reason = ex; } } } else { println("skipping: " + aDriver.getClass().getName()); } } }
4、擴展
既然我們知道JDBC是這樣創建數據庫連接的,我們能不能再擴展一下呢?如果我們自己也創建一個 java.sql.Driver 文件,自定義實現類MySQLDriver,那么,在獲取連接的前后就可以動態修改一些信息。
還是先在項目resources下創建文件,文件內容為自定義驅動類 com.jcc.java.spi.domyself.MySQLDriver
我們的 MySQLDriver 實現類,繼承自MySQL中的 NonRegisteringDriver ,還要實現 java.sql.Driver 接口。這樣,在調用connect方法的時候,就會調用到此類,但實際創建的過程還靠MySQL完成。
public class MySQLDriver extends NonRegisteringDriver implements Driver{ static { try { DriverManager.registerDriver(new MySQLDriver()); } catch (SQLException e) { e.printStackTrace(); } } public MySQLDriver() throws SQLException {} @Override public Connection connect(String url, Properties info) throws SQLException { System.out.println("准備創建數據庫連接.url:"+url); System.out.println("JDBC配置信息:"+info); //重置配置 info.setProperty("user", "root"); Connection connection = super.connect(url, info); System.out.println("數據庫連接創建完成!"+connection.toString()); return connection; } }
這樣的話,當我們獲取數據庫連接的時候,就會調用到這里。
--------------------輸出結果--------------------- 准備創建數據庫連接.url:jdbc:mysql:///consult?serverTimezone=UTC JDBC配置信息:{user=root, password=root} 數據庫連接創建完成!com.mysql.cj.jdbc.ConnectionImpl@7cf10a6f
三、SpringBoot中的應用
Spring Boot提供了一種快速的方式來創建可用於生產環境的基於Spring的應用程序。它基於Spring框架,更傾向於約定而不是配置,並且旨在使您盡快啟動並運行。
即便沒有任何配置文件,SpringBoot的Web應用都能正常運行。這種神奇的事情,SpringBoot正是依靠自動配置來完成。
說到這,我們必須關注一個東西: SpringFactoriesLoader,自動配置就是依靠它來加載的。
1、配置文件
SpringFactoriesLoader 來負責加載配置。我們打開這個類,看到它加載文件的路徑是: META-INF/spring.factories
筆者在項目中搜索這個文件,發現有4個Jar包都包含它:
- List itemspring-boot-2.1.9.RELEASE.jar
- spring-beans-5.1.10.RELEASE.jar
- spring-boot-autoconfigure-2.1.9.RELEASE.jar
- mybatis-spring-boot-autoconfigure-2.1.0.jar
那么它們里面都是些啥內容呢?其實就是一個個接口和類的映射。在這里筆者就不貼了,有興趣的小伙伴自己去看看。
比如在SpringBoot啟動的時候,要加載所有的 ApplicationContextInitializer ,那么就可以這樣做:
SpringFactoriesLoader.loadFactoryNames(ApplicationContextInitializer.class, classLoader)
2、加載文件
loadSpringFactories 就負責讀取所有的 spring.factories 文件內容。
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) { MultiValueMap<String, String> result = cache.get(classLoader); if (result != null) { return result; } try { //獲取所有spring.factories文件的路徑 Enumeration<URL> urls = lassLoader.getResources("META-INF/spring.factories"); result = new LinkedMultiValueMap<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); //加載文件並解析文件內容 UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); for (Map.Entry<?, ?> entry : properties.entrySet()) { String factoryClassName = ((String) entry.getKey()).trim(); for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) { result.add(factoryClassName, factoryName.trim()); } } } cache.put(classLoader, result); return result; } catch (IOException ex) { throw new IllegalArgumentException("Unable to load factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex); } }
可以看到,它並沒有采用JDK中的SPI機制來加載這些類,不過原理差不多。都是通過一個配置文件,加載並解析文件內容,然后通過反射創建實例。
3、參與其中
假如你希望參與到 SpringBoot 初始化的過程中,現在我們又多了一種方式。
我們也創建一個 spring.factories 文件,自定義一個初始化器。
org.springframework.context.ApplicationContextInitializer=com.youyouxunyin.config.context.MyContextInitializer
然后定義一個MyContextInitializer類
public class MyContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { System.out.println(configurableApplicationContext); } }
四、Dubbo中的應用
我們熟悉的Dubbo也不例外,它也是通過 SPI 機制加載所有的組件。同樣的,Dubbo 並未使用 Java 原生的 SPI 機制,而是對其進行了增強,使其能夠更好的滿足需求。在 Dubbo 中,SPI 是一個非常重要的模塊。基於 SPI,我們可以很容易的對 Dubbo 進行拓展。
關於原理,如果有小伙伴不熟悉,可以參閱筆者文章:
它的使用方式同樣是在 META-INF/services 創建文件並寫入相關類名。
關於使用場景,可以參考: SpringBoot+Dubbo集成ELK實戰
五、sentinel中的應用
通過SPI機制將META-INFO/servcie下配置好的默認責任鏈構造這加載出來,然后調用其builder()方法進行構建調用鏈
public final class SlotChainProvider { private static volatile SlotChainBuilder slotChainBuilder = null; /** * The load and pick process is not thread-safe, but it's okay since the method should be only invoked * via {@code lookProcessChain} in {@link com.alibaba.csp.sentinel.CtSph} under lock. * * @return new created slot chain */ public static ProcessorSlotChain newSlotChain() { if (slotChainBuilder != null) { return slotChainBuilder.build(); } // Resolve the slot chain builder SPI. slotChainBuilder = SpiLoader.of(SlotChainBuilder.class).loadFirstInstanceOrDefault(); if (slotChainBuilder == null) { // Should not go through here. RecordLog.warn("[SlotChainProvider] Wrong state when resolving slot chain builder, using default"); slotChainBuilder = new DefaultSlotChainBuilder(); } else { RecordLog.info("[SlotChainProvider] Global slot chain builder resolved: {}", slotChainBuilder.getClass().getCanonicalName()); } return slotChainBuilder.build(); } private SlotChainProvider() {} }
SpiLoader.of()
public static <T> SpiLoader<T> of(Class<T> service) { AssertUtil.notNull(service, "SPI class cannot be null"); AssertUtil.isTrue(service.isInterface() || Modifier.isAbstract(service.getModifiers()), "SPI class[" + service.getName() + "] must be interface or abstract class"); String className = service.getName(); SpiLoader<T> spiLoader = SPI_LOADER_MAP.get(className); if (spiLoader == null) { synchronized (SpiLoader.class) { spiLoader = SPI_LOADER_MAP.get(className); if (spiLoader == null) { SPI_LOADER_MAP.putIfAbsent(className, new SpiLoader<>(service)); spiLoader = SPI_LOADER_MAP.get(className); } } } return spiLoader; }
@Spi(isDefault = true) public class DefaultSlotChainBuilder implements SlotChainBuilder { @Override public ProcessorSlotChain build() { ProcessorSlotChain chain = new DefaultProcessorSlotChain(); List<ProcessorSlot> sortedSlotList = SpiLoader.of(ProcessorSlot.class).loadInstanceListSorted(); for (ProcessorSlot slot : sortedSlotList) { if (!(slot instanceof AbstractLinkedProcessorSlot)) { RecordLog.warn("The ProcessorSlot(" + slot.getClass().getCanonicalName() + ") is not an instance of AbstractLinkedProcessorSlot, can't be added into ProcessorSlotChain"); continue; } chain.addLast((AbstractLinkedProcessorSlot<?>) slot); } return chain; } }
責任鏈同樣是由spi機制加載出來的,上面的加載只會在第一次使用的時候加載,然后緩存到內從后,以后直接取即可。
至此,SPI機制的實現原理就分析完了。 雖然SPI我們日常開發中用的很少,但是至少了解了解還是有必要的。 例如: 一些框架實現中一般都會用到SPI機制。
vert.x內部也是大量使用SPI
轉自:https://zhuanlan.zhihu.com/p/59546945
https://blog.csdn.net/KingJin_CSDN_/article/details/103667359