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

接下來是實現(xiàn)的過程
第一步:創(chuàng)建spi-demo-contract項目,在resources目錄下新建如下目錄(MATE-INF/services)和文件(com.example.spidemocontract.spi.SpiTestDemoService)
- 修改com.example.spidemocontract.spi.SpiTestDemoService文件
- 新增第二步一樣位置的接口類,以及對應的實現(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(與依賴包的文件名稱完全一致,但內容指向了當前項目自定義的實現(xiàn)類)文件
- 實現(xiàn)SPI接口,自定義spi-demo項目的實現(xiàn)類(這里可以把優(yōu)先級調到最高)
第三步:在spi-demo項目中用ServiceLoader進行加載SPI接口補充說明:我們可以重寫聲明類的優(yōu)先級,來判斷需要用哪個實現(xiàn)類來處理。比如重寫一個優(yōu)先級=0最高優(yōu)先級,然后加載的時候默認只取第一個優(yōu)先級最高的,那我們重寫的自定義實現(xiàn)類就能覆蓋掉默認SPI實現(xiàn)類
詳細步驟拆分如下
- 第一步:創(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
- 新增第二步一樣位置的接口類,以及對應的實現(xiàn)類
/**
* 這個接口類完全對應resources/META-INF/services/com.example.spidemocontract.spi.impl.DefaultSpiTestDemoService
**/
public interface SpiTestDemoService {
void printLog();
int getOrder();
}
/**
* 將默認的設置為優(yōu)先級最低,這是默認的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(與依賴包的文件名稱完全一致,但內容指向了當前項目自定義的實現(xiàn)類)文件如下
com.example.spidemo.spi.OtherSpiTestDemoService
- 實現(xiàn)SPI接口,自定義spi-demo項目的實現(xiàn)類
/**
* 其他,把他優(yōu)先級設置的比較高
*/
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進行加載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
// 當前接口會在resource/META-INF/services目錄下對應文件com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper
public interface ConfigPropertySourcesProcessorHelper extends Ordered {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
- 當前SPI中的默認實現(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來進行排序優(yōu)先級,order最小的那個優(yōu)先級最高,只取第一個數(shù)據(jù)candidates.get(0)并返回。
因為自定義SPI實現(xiàn)優(yōu)先級可以設置得很高,所以就可以達到覆蓋默認實現(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)實例,然后進行排序,取優(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ù)如下
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 - 準備創(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方法調用執(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簡單分析如下
獲取所有注冊的驅動(每個驅動的都遍歷一下,其實就是最晚注冊那個就用那個了,如果失敗就往下一個找)
// 獲取所有注冊的驅動(每個驅動的都遍歷一下,其實就是最晚注冊那個就用那個了,如果失敗就往下一個找)
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());
}
}
到此這篇關于Java插件擴展機制之SPI案例講解的文章就介紹到這了,更多相關Java插件擴展機制之SPI內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
idea創(chuàng)建SpringBoot項目及注解配置相關應用小結
Spring Boot是Spring社區(qū)發(fā)布的一個開源項目,旨在幫助開發(fā)者快速并且更簡單的構建項目,Spring Boot框架,其功能非常簡單,便是幫助我們實現(xiàn)自動配置,本文給大家介紹idea創(chuàng)建SpringBoot項目及注解配置相關應用,感興趣的朋友跟隨小編一起看看吧2023-11-11
java.io.UnsupportedEncodingException異常的正確解決方法(親測有效!)
這篇文章主要給大家介紹了關于java.io.UnsupportedEncodingException異常的正確解決方法,文中介紹的辦法親測有效,java.io.UnsupportedEncodingException是Java編程語言中的一個異常類,表示指定的字符集不被支持,需要的朋友可以參考下2024-02-02
Springboot WebFlux集成Spring Security實現(xiàn)JWT認證的示例
這篇文章主要介紹了Springboot WebFlux集成Spring Security實現(xiàn)JWT認證的示例,幫助大家更好的理解和學習使用springboot框架,感興趣的朋友可以了解下2021-04-04
Java使用Lambda表達式查找list集合中是否包含某值問題
Java使用Lambda表達式查找list集合中是否包含某值的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
Spring-boot oauth2使用RestTemplate進行后臺自動登錄的實現(xiàn)
這篇文章主要介紹了Spring-boot oauth2使用RestTemplate進行后臺自動登錄的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
淺析Java中XPath和JsonPath以及SpEL的用法與對比
XPath,即XML路徑語言,是一種用于在XML文檔中查找信息的語言,JsonPath是從XPath中發(fā)展而來的,專門用于JSON數(shù)據(jù)格式,本文主要來講講他們的用法與區(qū)別,需要的可以參考下2023-11-11
關于@GetMapping和@GetMapping(value=““)的區(qū)別
這篇文章主要介紹了關于@GetMapping和@GetMapping(value=““)的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

