本文首發於 vivo互聯網技術 微信公衆號
連接:https://mp.weixin.qq.com/s/vpy5DJ-hhn0iOyp747oL5A
做者:姜柱html
SPI(Service Provider Interface),是JDK內置的一種服務提供發現機制,本文由淺入深地介紹了Java SPI機制。java
SPI(Service Provider Interface),是JDK內置的一種服務提供發現機制,能夠用來啓用框架擴展和替換組件,主要是被框架的開發人員使用,好比java.sql.Driver接口,其餘不一樣廠商能夠針對同一接口作出不一樣的實現,MySQL和PostgreSQL都有不一樣的實現提供給用戶,而Java的SPI機制能夠爲某個接口尋找服務實現。Java中SPI機制主要思想是將裝配的控制權移到程序以外,在模塊化設計中這個機制尤爲重要,其核心思想就是解耦。mysql
SPI與API區別:sql
API是調用並用於實現目標的類、接口、方法等的描述;apache
SPI是擴展和實現以實現目標的類、接口、方法等的描述;api
換句話說,API 爲操做提供特定的類、方法,SPI 經過操做來符合特定的類、方法。緩存
參考:https://stackoverflow.com/questions/2954372/difference-between-spi-and-api?answertab=votes#tab-top安全
SPI總體機制圖以下:微信
當服務的提供者提供了一種接口的實現以後,須要在classpath下的META-INF/services/目錄裏建立一個以服務接口命名的文件,這個文件裏的內容就是這個接口的具體的實現類。當其餘的程序須要這個服務的時候,就能夠經過查找這個jar包(通常都是以jar包作依賴)的META-INF/services/中的配置文件,配置文件中有接口的具體實現類名,能夠根據這個類名進行加載實例化,就可使用該服務了。JDK中查找服務的實現的工具類是:java.util.ServiceLoader。多線程
SPI擴展機制應用場景有不少,好比Common-Logging,JDBC,Dubbo等等。
SPI流程:
有關組織和公式定義接口標準
第三方提供具體實現: 實現具體方法, 配置 META-INF/services/${interface_name} 文件
開發者使用
好比JDBC場景下:
首先在Java中定義了接口java.sql.Driver,並無具體的實現,具體的實現都是由不一樣廠商提供。
在MySQL的jar包mysql-connector-java-6.0.6.jar中,能夠找到META-INF/services目錄,該目錄下會有一個名字爲java.sql.Driver的文件,文件內容是com.mysql.cj.jdbc.Driver,這裏面的內容就是針對Java中定義的接口的實現。
一樣在PostgreSQL的jar包PostgreSQL-42.0.0.jar中,也能夠找到一樣的配置文件,文件內容是org.postgresql.Driver,這是PostgreSQL對Java的java.sql.Driver的實現。
1.定義一個接口HelloSPI。
package com.vivo.study.spidemo.spi; public interface HelloSPI { void sayHello(); }
2.完成接口的多個實現。
package com.vivo.study.spidemo.spi.impl; import com.vivo.study.spidemo.spi.HelloSPI; public class ImageHello implements HelloSPI { public void sayHello() { System.out.println("Image Hello"); } }
package com.vivo.study.spidemo.spi.impl; import com.vivo.study.spidemo.spi.HelloSPI; public class TextHello implements HelloSPI { public void sayHello() { System.out.println("Text Hello"); } }
在META-INF/services/目錄裏建立一個以com.vivo.study.spidemo.spi.HelloSPI的文件,這個文件裏的內容就是這個接口的具體的實現類。
具體內容以下:
com.vivo.study.spidemo.spi.impl.ImageHello com.vivo.study.spidemo.spi.impl.TextHello
3.使用 ServiceLoader 來加載配置文件中指定的實現
package com.vivo.study.spidemo.test import java.util.ServiceLoader; import com.vivo.study.spidemo.spi.HelloSPI; public class SPIDemo { public static void main(String[] args) { ServiceLoader<HelloSPI> serviceLoader = ServiceLoader.load(HelloSPI.class); // 執行不一樣廠商的業務實現,具體根據業務需求配置 for (HelloSPI helloSPI : serviceLoader) { helloSPI.sayHello(); } } }
輸出結果以下:
Image Hello Text Hello
// ServiceLoader實現了Iterable接口,能夠遍歷全部的服務實現者 public final class ServiceLoader<S> implements Iterable<S> { // 查找配置文件的目錄 private static final String PREFIX = "META-INF/services/"; // 表示要被加載的服務的類或接口 private final Class<S> service; // 這個ClassLoader用來定位,加載,實例化服務提供者 private final ClassLoader loader; // 訪問控制上下文 private final AccessControlContext acc; // 緩存已經被實例化的服務提供者,按照實例化的順序存儲 private LinkedHashMap<String,S> providers = new LinkedHashMap<>(); // 迭代器 private LazyIterator lookupIterator; }
// 服務提供者查找的迭代器 public Iterator<S> iterator() { return new Iterator<S>() { Iterator<Map.Entry<String,S>> knownProviders = providers.entrySet().iterator(); // hasNext方法 public boolean hasNext() { if (knownProviders.hasNext()) return true; return lookupIterator.hasNext(); } // next方法 public S next() { if (knownProviders.hasNext()) return knownProviders.next().getValue(); return lookupIterator.next(); } }; }
// 服務提供者查找的迭代器 private class LazyIterator implements Iterator<S> { // 服務提供者接口 Class<S> service; // 類加載器 ClassLoader loader; // 保存實現類的url Enumeration<URL> configs = null; // 保存實現類的全名 Iterator<String> pending = null; // 迭代器中下一個實現類的全名 String nextName = null; public boolean hasNext() { 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; } public S next() { if (!hasNext()) { throw new NoSuchElementException(); } 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()); providers.put(cn, p); return p; } catch (Throwable x) { fail(service, "Provider " + cn + " could not be instantiated: " + x, x); } throw new Error(); // This cannot happen } }
首先,ServiceLoader實現了Iterable接口,因此它有迭代器的屬性,這裏主要都是實現了迭代器的hasNext和next方法。這裏主要都是調用的lookupIterator的相應hasNext和next方法,lookupIterator是懶加載迭代器。
其次,LazyIterator中的hasNext方法,靜態變量PREFIX就是」META-INF/services/」目錄,這也就是爲何須要在classpath下的META-INF/services/目錄裏建立一個以服務接口命名的文件。
最後,經過反射方法Class.forName()加載類對象,並用newInstance方法將類實例化,並把實例化後的類緩存到providers對象中,(LinkedHashMap<String,S>類型) 而後返回實例對象。
1.不能按需加載,須要遍歷全部的實現,並實例化,而後在循環中才能找到咱們須要的實現。若是不想用某些實現類,或者某些類實例化很耗時,它也被載入並實例化了,這就形成了浪費。
2.獲取某個實現類的方式不夠靈活,只能經過 Iterator 形式獲取,不能根據某個參數來獲取對應的實現類。
3.多個併發多線程使用 ServiceLoader 類的實例是不安全的。
針對以上的不足點,咱們在SPI機制選擇時,能夠考慮使用dubbo實現的SPI機制。
具體參考: http://dubbo.apache.org/zh-cn/blog/introduction-to-dubbo-spi.html
更多內容敬請關注 vivo 互聯網技術 微信公衆號
注:轉載文章請先與微信號:labs2020 聯繫。