Dubbo 源碼學習筆記 —— SPI的機制體現

dubbo官方文檔開發者指南中有這句話:

關於SPI,java相關百度熱詞集中在什麼是SPI,SPI API……
什麼是SPI?

java官方文檔描述:
service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.
…………
參考:

API和SPI的區別
網上最多的回答都是基於stackoverflow中的回答鋪展
What is the difference between Service Provider Interface (SPI) and Application Programming Interface (API)?
More specifically, for Java libraries, what makes them an API and/or SPI?

the API is the description of classes/interfaces/methods/... that you call and use to achieve a goal
the SPI is the description of classes/interfaces/methods/... that you extend and implement to achieve a goal

Put differently, the API tells you what a specific class/method does for you and the SPI tells you what you must do to conform.
Sometimes SPI and API overlap. For example in JDBC the Driver class is part of the SPI: If you simply want to use JDBC, you don't need to use it directly, but everyone who implements a JDBC driver must implement that class.
The Connection interface on the other hand is both SPI and API: You use it routinely when you use a JDBC driver and it needs to be implemented by the developer of the JDBC driver。
參考:

以上的一堆嘰裏呱啦無非其實是闡述的就是以下的機制

SPI開發編程機制:
SPI(Service Provider Interface),服務提供者擴展標準的接口,調用者可以通過提供SPI接口的具體實現完成調用者的"定製化"開發工作,不同於API(Application Programe Interface),調用者調用API爲了實現某功能,SPI採用模板方法的設計模式,在API設計中定義一個SPI接口,第三方使用此接口時可在META-INF下定義一個以接口全名命名的文件,文件內容爲第三方擴展此接口的文件名全稱(加載時通過classpath自動加載對應的實現類),這樣要求調用者提供具體實現來完整SPI接口提供方的功能。dubbo的開發設計除了在Service層和Config層採用的API方式,其他層面均採用SPI定義接口,採用此方式以Ioc的機制將api接口實現的一些細節交給實際調用者實現,框架變的可擴展而核心部分保持穩定。

示例:
dubbo 註冊中心層 dubbo-registry

定義了註冊接口RegistryFactory,,dubbo支持zookeeper,redis,multicast註冊中心,不同類型的註冊中心RegistryFactory通過實現getRegistry方法來初始化一個註冊中心鏈接實體。如下圖

四個不同類型的註冊中心實現可以看作四個服務廠商,分別看dubbo-registry-redis源碼和dubbo-registry-zookeeper源碼的實現,對應的工廠類實現方法
redis:

zookeeper:

相對複雜,初始化Registry時調用了AbstractRegistryFactory中的模板方法

如上,兩者分別實現了getRegistry(URL url)的方法返回不用的Registry實例
dubbo-registry-api作爲dubbo registry層的框架層提供RegisryFactory爲上下層返回對應的Registry實例進行上下層的程序流動,而通過SPI的方式提供了各種註冊中心的支持,這樣保證原框架結構不發生變化的情況下活性的擴展了多種服務註冊中心的支持。

另外dubbo的SPI實現是對jdk本身的SPI的改善體現,參考官方文檔:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章