Java插件擴(kuò)展機(jī)制之SPI案例講解
什么是SPI
SPI ,全稱為 Service Provider Interface,是一種服務(wù)發(fā)現(xiàn)機(jī)制。其為框架提供了一個對外可擴(kuò)展的能力。
與 接口類-實現(xiàn)類 提供的RPC 方式有什么區(qū)別?
- 傳統(tǒng)的接口類實現(xiàn)形式為如下
public interface AdOpFromApolloService {}
public class AdOpFromDbServiceImpl implements AdOpFromDbService {}
假設(shè)我們需要實現(xiàn)RPC,是怎么做的?
RPC會在對應(yīng)的接口類AdOpFromApolloService新增一個注解用于標(biāo)注是RPC類,然后將當(dāng)前類放在依賴包提供給其他項目來通過接口類進(jìn)行調(diào)用
簡而言之:RPC調(diào)用中只提供接口類,然后讓第三方調(diào)用(第三方只調(diào),不寫實現(xiàn))
那RPC究竟跟SPI什么關(guān)系?
- SPI:提供接口,第三方引用包之后可重寫或用默認(rèn)的SPI接口的實現(xiàn)。
- RPC:提供接口,但是實現(xiàn)是私有的,不對外開放重寫能力。
SPI的應(yīng)用場景
框架實現(xiàn)案例:
- Spring擴(kuò)展插件實現(xiàn)。如JDCB
- 中間件擴(kuò)展插件實現(xiàn)。如Dubbo、Apollo
- 開發(fā)過程中舉例:實現(xiàn)一個攔截器,并用SPI機(jī)制來擴(kuò)展其攔截方式(比如全量攔截、每分鐘攔截多少、攔截比例多少、攔截的日志是log打印還是落庫、落es)
怎么實現(xiàn)一個SPI?
接下來用兩個項目模塊來講解SPI的用法,先看項目結(jié)構(gòu)圖如下

接下來是實現(xiàn)的過程
第一步:創(chuàng)建spi-demo-contract項目,在resources目錄下新建如下目錄(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService)
- 修改com.example.spidemocontract.spi.SpiTestDemoService文件
- 新增第二步一樣位置的接口類,以及對應(yīng)的實現(xiàn)類
第二步:創(chuàng)建spi-demo項目,然后引入spi-demo-contract依賴
- 在resources目錄下新建如下目錄(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService),文件名跟spi-demo-contract的完全一致
- 修改com.example.spidemocontract.spi.SpiTestDemoService(與依賴包的文件名稱完全一致,但內(nèi)容指向了當(dāng)前項目自定義的實現(xiàn)類)文件
- 實現(xiàn)SPI接口,自定義spi-demo項目的實現(xiàn)類(這里可以把優(yōu)先級調(diào)到最高)
第三步:在spi-demo項目中用ServiceLoader進(jìn)行加載SPI接口補充說明:我們可以重寫聲明類的優(yōu)先級,來判斷需要用哪個實現(xiàn)類來處理。比如重寫一個優(yōu)先級=0最高優(yōu)先級,然后加載的時候默認(rèn)只取第一個優(yōu)先級最高的,那我們重寫的自定義實現(xiàn)類就能覆蓋掉默認(rèn)SPI實現(xiàn)類
詳細(xì)步驟拆分如下
- 第一步:創(chuàng)建spi-demo-contract項目,在resources目錄下新建如下目錄(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService)
-- resources ---- META-INF -------- services ------------ com.example.spidemocontract.spi.SpiTestDemoService
- 修改com.example.spidemocontract.spi.SpiTestDemoService文件如下
com.example.spidemocontract.spi.impl.DefaultSpiTestDemoService
- 新增第二步一樣位置的接口類,以及對應(yīng)的實現(xiàn)類
/**
* 這個接口類完全對應(yīng)resources/META-INF/services/com.example.spidemocontract.spi.impl.DefaultSpiTestDemoService
**/
public interface SpiTestDemoService {
void printLog();
int getOrder();
}
/**
* 將默認(rèn)的設(shè)置為優(yōu)先級最低,這是默認(rèn)的SPI接口的實現(xiàn)類
*/
public class DefaultSpiTestDemoService implements SpiTestDemoService {
@Override
public int getOrder() {
return Integer.MAX_VALUE;
}
@Override
public void printLog() {
System.out.println("輸出 DefaultSpiTestDemoService log");
}
}
- 第二步:創(chuàng)建spi-demo項目,然后引入spi-demo-contract依賴
<dependency>
<groupId>com.example</groupId>
<artifactId>spi-demo-contract</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
- 在resources目錄下新建如下目錄(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService),文件名跟spi-demo-contract的完全一致
-- resources ---- META-INF -------- services ------------ com.example.spidemocontract.spi.SpiTestDemoService
- 修改com.example.spidemocontract.spi.SpiTestDemoService(與依賴包的文件名稱完全一致,但內(nèi)容指向了當(dāng)前項目自定義的實現(xiàn)類)文件如下
com.example.spidemo.spi.OtherSpiTestDemoService
- 實現(xiàn)SPI接口,自定義spi-demo項目的實現(xiàn)類
/**
* 其他,把他優(yōu)先級設(shè)置的比較高
*/
public class OtherSpiTestDemoService implements SpiTestDemoService {
// 后面我們用SPI類加載器獲取時,會根據(jù)order排序,越小優(yōu)先級越高
@Override
public int getOrder() {
return 0;
}
@Override
public void printLog() {
System.out.println("輸出 OtherSpiTestDemoService log");
}
}
- 第三步:在spi-demo項目中用ServiceLoader進(jìn)行加載SPI接口
public static void main(String[] args) {
// 加載SPI
Iterator<SpiTestDemoService> iterator = ServiceLoader.load(SpiTestDemoService.class).iterator();
// 實現(xiàn)了ordered,會根據(jù)ordered返回值排序,優(yōu)先級越高,越先取出來
List<SpiTestDemoService> list = Lists.newArrayList(iterator)
.stream().sorted(Comparator.comparing(SpiTestDemoService::getOrder))
.collect(Collectors.toList());
for (SpiTestDemoService item : list) {
item.printLog();
}
}
中間件是怎么實現(xiàn)SPI的?
Apollo-Client中的實現(xiàn)
- Apollo-Client初始化過程中,有一個SPI接口ConfigPropertySourcesProcessorHelper
// 當(dāng)前接口會在resource/META-INF/services目錄下對應(yīng)文件com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper
public interface ConfigPropertySourcesProcessorHelper extends Ordered {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
- 當(dāng)前SPI中的默認(rèn)實現(xiàn)為
public class DefaultConfigPropertySourcesProcessorHelper implements ConfigPropertySourcesProcessorHelper {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// .....各種注冊bean,初始化的流程
}
@Override
public int getOrder() {
// 優(yōu)先級排序置為最低。方便其他自定義spi實現(xiàn)類能夠覆蓋
return Ordered.LOWEST_PRECEDENCE;
}
}
- 怎么選擇加載出自定義的SPI實現(xiàn)類
通過ServiceLoader.load(Xxxx.class)加載出所有實例,然后根據(jù)order來進(jìn)行排序優(yōu)先級,order最小的那個優(yōu)先級最高,只取第一個數(shù)據(jù)candidates.get(0)并返回。
因為自定義SPI實現(xiàn)優(yōu)先級可以設(shè)置得很高,所以就可以達(dá)到覆蓋默認(rèn)實現(xiàn)的目的
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實現(xiàn)實例,然后進(jìn)行排序,取優(yōu)先級最高的那個
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中的實現(xiàn)
- JDBC SPI中配置文件resources/META-INF/services/java.sql.Driver,并設(shè)置參數(shù)如下
com.example.app.driver.MyDriver
- 繼承SPI接口java.sql.Driver,實現(xiàn)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 - 準(zhǔn)備創(chuàng)建數(shù)據(jù)庫連接.url:" + url);
System.out.println("JDBC配置信息:" + info);
info.setProperty("user", "root");
Connection connection = super.connect(url, info);
System.out.println("MyDriver - 數(shù)據(jù)庫連接創(chuàng)建完成!" + connection.toString());
return connection;
}
}
- 寫main方法調(diào)用執(zhí)行剛實現(xiàn)的自定義SPI實現(xiàn)
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);
- JDBC如何使用SPI簡單分析如下
獲取所有注冊的驅(qū)動(每個驅(qū)動的都遍歷一下,其實就是最晚注冊那個就用那個了,如果失敗就往下一個找)
// 獲取所有注冊的驅(qū)動(每個驅(qū)動的都遍歷一下,其實就是最晚注冊那個就用那個了,如果失敗就往下一個找)
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());
}
}
到此這篇關(guān)于Java插件擴(kuò)展機(jī)制之SPI案例講解的文章就介紹到這了,更多相關(guān)Java插件擴(kuò)展機(jī)制之SPI內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實現(xiàn)前端驗證碼圖片生成和校驗
這篇文章主要為大家詳細(xì)介紹了SpringBoot實現(xiàn)前端驗證碼圖片生成和校驗,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
mybatis中點擊mapper接口快速定位到對應(yīng)xml中sql方式
這篇文章主要介紹了mybatis中點擊mapper接口快速定位到對應(yīng)xml中sql方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
eclipse中自動生成構(gòu)造函數(shù)的兩種方法
下面小編就為大家?guī)硪黄猠clipse中自動生成構(gòu)造函數(shù)的兩種方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
MyBatis?resultMap?id標(biāo)簽的錯誤使用方式
這篇文章主要介紹了MyBatis?resultMap?id標(biāo)簽的錯誤使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
Java實現(xiàn)STL中的全排列函數(shù)next_permutation()
在算法競賽中,全排列問題是一個經(jīng)典且常見的題目,傳統(tǒng)的遞歸方法在處理較大的n時會遇到堆棧內(nèi)存限制的問題,本文介紹了一種避免遞歸,使用next_permutation函數(shù)實現(xiàn)全排列的方法,感興趣的朋友跟隨小編一起看看吧2024-09-09
springboot?加載本地jar到maven的實現(xiàn)方法
如何在SpringBoot項目中加載本地jar到Maven本地倉庫,使用Maven的install-file目標(biāo)來實現(xiàn),本文結(jié)合實例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2025-01-01

