偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Spring Boot 插件化開發(fā)模式

開發(fā) 前端
插件化開發(fā)模式正在很多編程語言或技術框架中得以廣泛的應用實踐,比如大家熟悉的jenkins,docker可視化管理平臺rancher,以及日常編碼使用的編輯器idea,vscode等。

一、前言

插件化開發(fā)模式正在很多編程語言或技術框架中得以廣泛的應用實踐,比如大家熟悉的jenkins,docker可視化管理平臺rancher,以及日常編碼使用的編輯器idea,vscode等。

隨處可見的帶有熱插拔功能的插件,讓系統(tǒng)像插了翅膀一樣,大大提升了系統(tǒng)的擴展性和伸縮性,也拓展了系統(tǒng)整體的使用價值,那么為什么要使用插件呢?

1.1 使用插件的好處

1.1.1 模塊解耦

實現(xiàn)服務模塊之間解耦的方式有很多,但是插件來說,其解耦的程度似乎更高,而且更靈活,可定制化、個性化更好。

舉例來說,代碼中可以使用設計模式來選擇使用哪種方式發(fā)送短信給下單完成的客戶,問題是各個短信服務商并不一定能保證在任何情況下都能發(fā)送成功,怎么辦呢?這時候設計模式也沒法幫你解決這個問題,如果使用定制化插件的方式,結合外部配置參數(shù),假設系統(tǒng)中某種短信發(fā)送不出去了,這時候就可以利用插件動態(tài)植入,切換為不同的廠商發(fā)短信了。

1.1.2 提升擴展性和開放性

以spring來說,之所以具備如此廣泛的生態(tài),與其自身內(nèi)置的各種可擴展的插件機制是分不開的,試想為什么使用了spring框架之后可以很方便的對接其他中間件,那就是spring框架提供了很多基于插件化的擴展點。

插件化機制讓系統(tǒng)的擴展性得以提升,從而可以豐富系統(tǒng)的周邊應用生態(tài)。

1.1.3 方便第三方接入

有了插件之后,第三方應用或系統(tǒng)如果要對接自身的系統(tǒng),直接基于系統(tǒng)預留的插件接口完成一套適合自己業(yè)務的實現(xiàn)即可,而且對自身系統(tǒng)的侵入性很小,甚至可以實現(xiàn)基于配置參數(shù)的熱加載,方便靈活,開箱即用。

1.2 插件化常用實現(xiàn)思路

以java為例,這里結合實際經(jīng)驗,整理一些常用的插件化實現(xiàn)思路:

  • spi機制;
  • 約定配置和目錄,利用反射配合實現(xiàn);
  • springboot中的Factories機制;
  • java agent(探針)技術;
  • spring內(nèi)置擴展點;
  • 第三方插件包,例如:spring-plugin-core;
  • spring aop技術。

二、Java常用插件實現(xiàn)方案

2.1 serviceloader方式

serviceloader是java提供的spi模式的實現(xiàn)。按照接口開發(fā)實現(xiàn)類,而后配置,java通過ServiceLoader來實現(xiàn)統(tǒng)一接口不同實現(xiàn)的依次調用。而java中最經(jīng)典的serviceloader的使用就是Java的spi機制。

2.1.1 java spi

SPI全稱 Service Provider Interface ,是JDK內(nèi)置的一種服務發(fā)現(xiàn)機制,SPI是一種動態(tài)替換擴展機制,比如有個接口,你想在運行時動態(tài)給他添加實現(xiàn),你只需按照規(guī)范給他添加一個實現(xiàn)類即可。比如大家熟悉的jdbc中的Driver接口,不同的廠商可以提供不同的實現(xiàn),有mysql的,也有oracle的,而Java的SPI機制就可以為某個接口尋找服務的實現(xiàn)。

下面用一張簡圖說明下SPI機制的原理。

圖片圖片

2.1.2 java spi 簡單案例

如下工程目錄,在某個應用工程中定義一個插件接口,而其他應用工程為了實現(xiàn)這個接口,只需要引入當前工程的jar包依賴進行實現(xiàn)即可,這里為了演示我就將不同的實現(xiàn)直接放在同一個工程下。

圖片圖片

定義接口:

public interface MessagePlugin {
 
    public String sendMsg(Map msgMap);
 
}

定義兩個不同的實現(xiàn):

public class AliyunMsg implements MessagePlugin {

    @Override
    public String sendMsg(Map msgMap) {
        System.out.println("aliyun sendMsg");
        return"aliyun sendMsg";
    }
}
publicclass TencentMsg implements MessagePlugin {

    @Override
    public String sendMsg(Map msgMap) {
        System.out.println("tencent sendMsg");
        return"tencent sendMsg";
    }
}

在resources目錄按照規(guī)范要求創(chuàng)建文件目錄,并填寫實現(xiàn)類的全類名。

圖片圖片

自定義服務加載類:

public static void main(String[] args) {
        ServiceLoader<MessagePlugin> serviceLoader = ServiceLoader.load(MessagePlugin.class);
        Iterator<MessagePlugin> iterator = serviceLoader.iterator();
        Map map = new HashMap();
        while (iterator.hasNext()){
            MessagePlugin messagePlugin = iterator.next();
            messagePlugin.sendMsg(map);
        }
    }

運行上面的程序后,可以看到下面的效果,這就是說,使用ServiceLoader的方式可以加載到不同接口的實現(xiàn),業(yè)務中只需要根據(jù)自身的需求,結合配置參數(shù)的方式就可以靈活的控制具體使用哪一個實現(xiàn)。

圖片圖片

2.2 自定義配置約定方式

serviceloader其實是有缺陷的,在使用中必須在META-INF里定義接口名稱的文件,在文件中才能寫上實現(xiàn)類的類名,如果一個項目里插件化的東西比較多,那很可能會出現(xiàn)越來越多配置文件的情況。所以在結合實際項目使用時,可以考慮下面這種實現(xiàn)思路:

  • A應用定義接口;
  • B,C,D等其他應用定義服務實現(xiàn);
  • B,C,D應用實現(xiàn)后達成SDK的jar;
  • A應用引用SDK或者將SDK放到某個可以讀取到的目錄下;
  • A應用讀取并解析SDK中的實現(xiàn)類。

在上文中案例基礎上,我們做如下調整。

2.2.1 添加配置文件

在配置文件中,將具體的實現(xiàn)類配置進去。

server :
  port : 8081
impl:
  name : com.congge.plugins.spi.MessagePlugin
  clazz :
    - com.congge.plugins.impl.TencentMsg
    - com.congge.plugins.impl.AliyunMsg
2.2.2 自定義配置文件加載類

通過這個類,將上述配置文件中的實現(xiàn)類封裝到類對象中,方便后續(xù)使用。

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("impl")
@ToString
publicclass ClassImpl {
    @Getter
    @Setter
    String name;

    @Getter
    @Setter
    String[] clazz;
}
2.2.3 自定義測試接口

使用上述的封裝對象通過類加載的方式動態(tài)的在程序中引入。

import com.congge.config.ClassImpl;
import com.congge.plugins.spi.MessagePlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
publicclass SendMsgController {

    @Autowired
    ClassImpl classImpl;

    //localhost:8081/sendMsg
    @GetMapping("/sendMsg")
    public String sendMsg() throws Exception{
        for (int i=0;i<classImpl.getClazz().length;i++) {
            Class pluginClass= Class.forName(classImpl.getClazz()[i]);
            MessagePlugin messagePlugin = (MessagePlugin) pluginClass.newInstance();
            messagePlugin.sendMsg(new HashMap());
        }
        return"success";
    }

}
2.2.4 啟動類
@EnableConfigurationProperties({ClassImpl.class})
@SpringBootApplication
public class PluginApp {
 
    public static void main(String[] args) {
        SpringApplication.run(PluginApp.class,args);
    }
 
}

啟動工程代碼后,調用接口:localhost:8081/sendMsg,在控制臺中可以看到下面的輸出信息,即通過這種方式也可以實現(xiàn)類似serviceloader的方式,不過在實際使用時,可以結合配置參數(shù)進行靈活的控制。

圖片

2.3 自定義配置讀取依賴jar的方式

更進一步,在很多場景下,可能我們并不想直接在工程中引入接口實現(xiàn)的依賴包,這時候可以考慮通過讀取指定目錄下的依賴jar的方式,利用反射的方式進行動態(tài)加載,這也是生產(chǎn)中一種比較常用的實踐經(jīng)驗。

具體實踐來說,主要為下面的步驟:

  • 應用A定義服務接口;
  • 應用B,C,D等實現(xiàn)接口(或者在應用內(nèi)部實現(xiàn)相同的接口);
  • 應用B,C,D打成jar,放到應用A約定的讀取目錄下;
  • 應用A加載約定目錄下的jar,通過反射加載目標方法。

在上述的基礎上,按照上面的實現(xiàn)思路來實現(xiàn)一下。

2.3.1 創(chuàng)建約定目錄

在當前工程下創(chuàng)建一個lib目錄,并將依賴的jar放進去。

圖片

2.3.2 新增讀取jar的工具類

添加一個工具類,用于讀取指定目錄下的jar,并通過反射的方式,結合配置文件中的約定配置進行反射方法的執(zhí)行。

@Component
publicclass ServiceLoaderUtils {

    @Autowired
    ClassImpl classImpl;


    public static void loadJarsFromAppFolder() throws Exception {
        String path = "E:\\code-self\\bitzpp\\lib";
        File f = new File(path);
        if (f.isDirectory()) {
            for (File subf : f.listFiles()) {
                if (subf.isFile()) {
                    loadJarFile(subf);
                }
            }
        } else {
            loadJarFile(f);
        }
    }

    public static void loadJarFile(File path) throws Exception {
        URL url = path.toURI().toURL();
        // 可以獲取到AppClassLoader,可以提到前面,不用每次都獲取一次
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        // 加載
        //Method method = URLClassLoader.class.getDeclaredMethod("sendMsg", Map.class);
        Method method = URLClassLoader.class.getMethod("sendMsg", Map.class);

        method.setAccessible(true);
        method.invoke(classLoader, url);
    }

    public  void main(String[] args) throws Exception{
        System.out.println(invokeMethod("hello"));;
    }

    public String doExecuteMethod() throws Exception{
        String path = "E:\\code-self\\bitzpp\\lib";
        File f1 = new File(path);
        Object result = null;
        if (f1.isDirectory()) {
            for (File subf : f1.listFiles()) {
                //獲取文件名稱
                String name = subf.getName();
                String fullPath = path + "\\" + name;
                //執(zhí)行反射相關的方法
                //ServiceLoaderUtils serviceLoaderUtils = new ServiceLoaderUtils();
                //result = serviceLoaderUtils.loadMethod(fullPath);
                File f = new File(fullPath);
                URL urlB = f.toURI().toURL();
                URLClassLoader classLoaderA = new URLClassLoader(new URL[]{urlB}, Thread.currentThread()
                        .getContextClassLoader());
                String[] clazz = classImpl.getClazz();
                for(String claName : clazz){
                    if(name.equals("biz-pt-1.0-SNAPSHOT.jar")){
                        if(!claName.equals("com.congge.spi.BitptImpl")){
                            continue;
                        }
                        Class<?> loadClass = classLoaderA.loadClass(claName);
                        if(Objects.isNull(loadClass)){
                            continue;
                        }
                        //獲取實例
                        Object obj = loadClass.newInstance();
                        Map map = new HashMap();
                        //獲取方法
                        Method method=loadClass.getDeclaredMethod("sendMsg",Map.class);
                        result = method.invoke(obj,map);
                        if(Objects.nonNull(result)){
                            break;
                        }
                    }elseif(name.equals("miz-pt-1.0-SNAPSHOT.jar")){
                        if(!claName.equals("com.congge.spi.MizptImpl")){
                            continue;
                        }
                        Class<?> loadClass = classLoaderA.loadClass(claName);
                        if(Objects.isNull(loadClass)){
                            continue;
                        }
                        //獲取實例
                        Object obj = loadClass.newInstance();
                        Map map = new HashMap();
                        //獲取方法
                        Method method=loadClass.getDeclaredMethod("sendMsg",Map.class);
                        result = method.invoke(obj,map);
                        if(Objects.nonNull(result)){
                            break;
                        }
                    }
                }
                if(Objects.nonNull(result)){
                    break;
                }
            }
        }
        return result.toString();
    }

    public Object loadMethod(String fullPath) throws Exception{
        File f = new File(fullPath);
        URL urlB = f.toURI().toURL();
        URLClassLoader classLoaderA = new URLClassLoader(new URL[]{urlB}, Thread.currentThread()
                .getContextClassLoader());
        Object result = null;
        String[] clazz = classImpl.getClazz();
        for(String claName : clazz){
            Class<?> loadClass = classLoaderA.loadClass(claName);
            if(Objects.isNull(loadClass)){
                continue;
            }
            //獲取實例
            Object obj = loadClass.newInstance();
            Map map = new HashMap();
            //獲取方法
            Method method=loadClass.getDeclaredMethod("sendMsg",Map.class);
            result = method.invoke(obj,map);
            if(Objects.nonNull(result)){
                break;
            }
        }
        return result;
    }


    public static String invokeMethod(String text) throws Exception{
        String path = "E:\\code-self\\bitzpp\\lib\\miz-pt-1.0-SNAPSHOT.jar";
        File f = new File(path);
        URL urlB = f.toURI().toURL();
        URLClassLoader classLoaderA = new URLClassLoader(new URL[]{urlB}, Thread.currentThread()
                .getContextClassLoader());
        Class<?> product = classLoaderA.loadClass("com.congge.spi.MizptImpl");
        //獲取實例
        Object obj = product.newInstance();
        Map map = new HashMap();
        //獲取方法
        Method method=product.getDeclaredMethod("sendMsg",Map.class);
        //執(zhí)行方法
        Object result1 = method.invoke(obj,map);
        // TODO According to the requirements , write the implementation code.
        return result1.toString();
    }

    public static String getApplicationFolder() {
        String path = ServiceLoaderUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        returnnew File(path).getParent();
    }



}
2.3.3 添加測試接口

添加如下測試接口:

@GetMapping("/sendMsgV2")
public String index() throws Exception {
    String result = serviceLoaderUtils.doExecuteMethod();
    return result;
}

以上全部完成之后,啟動工程,測試一下該接口,仍然可以得到預期結果。

圖片圖片

在上述的實現(xiàn)中還是比較粗糙的,實際運用時,還需要做較多的優(yōu)化改進以滿足實際的業(yè)務需要,比如接口傳入類型參數(shù)用于控制具體使用哪個依賴包的方法進行執(zhí)行等。

三、SpringBoot中的插件化實現(xiàn)

在大家使用較多的springboot框架中,其實框架自身提供了非常多的擴展點,其中最適合做插件擴展的莫過于spring.factories的實現(xiàn)。

3.1 Spring Boot中的SPI機制

在Spring中也有一種類似與Java SPI的加載機制。它在META-INF/spring.factories文件中配置接口的實現(xiàn)類名稱,然后在程序中讀取這些配置文件并實例化,這種自定義的SPI機制是Spring Boot Starter實現(xiàn)的基礎。

3.2 Spring Factories實現(xiàn)原理

spring-core包里定義了SpringFactoriesLoader類,這個類實現(xiàn)了檢索META-INF/spring.factories文件,并獲取指定接口的配置的功能。在這個類中定義了兩個對外的方法:

  • loadFactories 根據(jù)接口類獲取其實現(xiàn)類的實例,這個方法返回的是對象列表;
  • loadFactoryNames 根據(jù)接口獲取其接口類的名稱,這個方法返回的是類名的列表。

上面的兩個方法的關鍵都是從指定的ClassLoader中獲取spring.factories文件,并解析得到類名列表,具體代碼如下:

public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    try {
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        List<String> result = new ArrayList<String>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    }
    catch (IOException ex) {
        thrownew IllegalArgumentException("Unable to load [" + factoryClass.getName() +
                "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

從代碼中我們可以知道,在這個方法中會遍歷整個ClassLoader中所有jar包下的spring.factories文件,就是說我們可以在自己的jar中配置spring.factories文件,不會影響到其它地方的配置,也不會被別人的配置覆蓋。

spring.factories的是通過Properties解析得到的,所以我們在寫文件中的內(nèi)容都是安裝下面這種方式配置的:

com.xxx.interface=com.xxx.classname

如果一個接口希望配置多個實現(xiàn)類,可以使用’,’進行分割。

3.3 Spring Factories案例實現(xiàn)

接下來看一個具體的案例實現(xiàn)來體驗下Spring Factories的使用。

3.3.1 定義一個服務接口

自定義一個接口,里面添加一個方法:

public interface SmsPlugin {
 
    public void sendMessage(String message);
 
}
3.3.2 定義2個服務實現(xiàn)

實現(xiàn)類1

public class BizSmsImpl implements SmsPlugin {
 
    @Override
    public void sendMessage(String message) {
        System.out.println("this is BizSmsImpl sendMessage..." + message);
    }
}

實現(xiàn)類2

public class SystemSmsImpl implements SmsPlugin {
 
    @Override
    public void sendMessage(String message) {
        System.out.println("this is SystemSmsImpl sendMessage..." + message);
    }
}
3.3.3 添加spring.factories文件

在resources目錄下,創(chuàng)建一個名叫:META-INF的目錄,然后在該目錄下定義一個spring.factories的配置文件,內(nèi)容如下,其實就是配置了服務接口,以及兩個實現(xiàn)類的全類名的路徑。

com.congge.plugin.spi.SmsPlugin=\
com.congge.plugin.impl.SystemSmsImpl,\
com.congge.plugin.impl.BizSmsImpl
3.3.4 添加自定義接口

添加一個自定義的接口,有沒有發(fā)現(xiàn),這里和java 的spi有點類似,只不過是這里換成了SpringFactoriesLoader去加載服務。

@GetMapping("/sendMsgV3")
public String sendMsgV3(String msg) throws Exception{
    List<SmsPlugin> smsServices= SpringFactoriesLoader.loadFactories(SmsPlugin.class, null);
    for(SmsPlugin smsService : smsServices){
        smsService.sendMessage(msg);
    }
    return "success";
}

啟動工程之后,調用一下該接口進行測試,localhost:8087/sendMsgV3?msg=hello,通過控制臺,可以看到,這種方式能夠正確獲取到系統(tǒng)中可用的服務實現(xiàn)。

圖片圖片

利用spring的這種機制,可以很好的對系統(tǒng)中的某些業(yè)務邏輯通過插件化接口的方式進行擴展實現(xiàn)。

四、插件化機制案例實戰(zhàn)

結合上面掌握的理論知識,下面基于Java SPI機制進行一個接近真實使用場景的完整的操作步驟。

4.1 案例背景

  • 3個微服務模塊,在A模塊中有個插件化的接口;
  • 在A模塊中的某個接口,需要調用插件化的服務實現(xiàn)進行短信發(fā)送;
  • 可以通過配置文件配置參數(shù)指定具體的哪一種方式發(fā)送短信;
  • 如果沒有加載到任何插件,將走A模塊在默認的發(fā)短信實現(xiàn)。
4.1.1 模塊結構

1、biz-pp,插件化接口工程;

2、bitpt,aliyun短信發(fā)送實現(xiàn);

3、miz-pt,tencent短信發(fā)送實現(xiàn)。

4.1.2 整體實現(xiàn)思路

本案例完整的實現(xiàn)思路參考如下:

  • biz-pp定義服務接口,并提供出去jar被其他實現(xiàn)工程依賴;
  • bitpt與miz-pt依賴biz-pp的jar并實現(xiàn)SPI中的方法;
  • bitpt與miz-pt按照API規(guī)范實現(xiàn)完成后,打成jar包,或者安裝到倉庫中;
  • biz-pp在pom中依賴bitpt與miz-pt的jar,或者通過啟動加載的方式即可得到具體某個實現(xiàn)。

4.2 biz-pp 關鍵代碼實現(xiàn)過程

4.2.1 添加服務接口
public interface MessagePlugin {
 
    public String sendMsg(Map msgMap);
 
}
4.2.2 打成jar包并安裝到倉庫

這一步比較簡單就不展開了。

4.2.3 自定義服務加載工具類

這個類,可以理解為在真實的業(yè)務編碼中,可以根據(jù)業(yè)務定義的規(guī)則,具體加載哪個插件的實現(xiàn)類進行發(fā)送短信的操作。

import com.congge.plugin.spi.MessagePlugin;
import com.congge.spi.BitptImpl;
import com.congge.spi.MizptImpl;

import java.util.*;

publicclass PluginFactory {

    public void installPlugin(){
        Map context = new LinkedHashMap();
        context.put("_userId","");
        context.put("_version","1.0");
        context.put("_type","sms");
        ServiceLoader<MessagePlugin> serviceLoader = ServiceLoader.load(MessagePlugin.class);
        Iterator<MessagePlugin> iterator = serviceLoader.iterator();
        while (iterator.hasNext()){
            MessagePlugin messagePlugin = iterator.next();
            messagePlugin.sendMsg(context);
        }
    }

    public static MessagePlugin getTargetPlugin(String type){
        ServiceLoader<MessagePlugin> serviceLoader = ServiceLoader.load(MessagePlugin.class);
        Iterator<MessagePlugin> iterator = serviceLoader.iterator();
        List<MessagePlugin> messagePlugins = new ArrayList<>();
        while (iterator.hasNext()){
            MessagePlugin messagePlugin = iterator.next();
            messagePlugins.add(messagePlugin);
        }
        MessagePlugin targetPlugin = null;
        for (MessagePlugin messagePlugin : messagePlugins) {
            boolean findTarget = false;
            switch (type) {
                case"aliyun":
                    if (messagePlugin instanceof BitptImpl){
                        targetPlugin = messagePlugin;
                        findTarget = true;
                        break;
                    }
                case"tencent":
                    if (messagePlugin instanceof MizptImpl){
                        targetPlugin = messagePlugin;
                        findTarget = true;
                        break;
                    }
            }
            if(findTarget) break;
        }
        return targetPlugin;
    }

    public static void main(String[] args) {
        new PluginFactory().installPlugin();
    }


}
4.2.4 自定義接口
@RestController
publicclass SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private ServiceLoaderUtils serviceLoaderUtils;

    //localhost:8087/sendMsg?msg=sendMsg
    @GetMapping("/sendMsg")
    public String sendMessage(String msg){
        return smsService.sendMsg(msg);
    }

}
4.2.5 接口實現(xiàn)
@Service
publicclass SmsService {

    @Value("${msg.type}")
    private String msgType;

    @Autowired
    private DefaultSmsService defaultSmsService;

    public String sendMsg(String msg) {
        MessagePlugin messagePlugin = PluginFactory.getTargetPlugin(msgType);
        Map paramMap = new HashMap();
        if(Objects.nonNull(messagePlugin)){
            return messagePlugin.sendMsg(paramMap);
        }
        return defaultSmsService.sendMsg(paramMap);
    }
}
4.2.6 添加服務依賴

在該模塊中,需要引入對具體實現(xiàn)的兩個工程的jar依賴(也可以通過啟動加載的命令方式)。

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--依賴具體的實現(xiàn)-->
    <dependency>
        <groupId>com.congge</groupId>
        <artifactId>biz-pt</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>com.congge</groupId>
        <artifactId>miz-pt</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

</dependencies>

biz-pp的核心代碼實現(xiàn)就到此結束了,后面再具體測試的時候再繼續(xù)。

4.3 bizpt 關鍵代碼實現(xiàn)過程

接下來就是插件化機制中具體的SPI實現(xiàn)過程,兩個模塊的實現(xiàn)步驟完全一致,挑選其中一個說明,工程目錄結構如下:

圖片

4.3.1 添加對biz-app的jar的依賴

將上面biz-app工程打出來的jar依賴過來。

<dependencies>
    <dependency>
        <groupId>com.congge</groupId>
        <artifactId>biz-app</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>
4.3.2 添加MessagePlugin接口的實現(xiàn)
public class BitptImpl implements MessagePlugin {
 
    @Override
    public String sendMsg(Map msgMap) {
        Object userId = msgMap.get("userId");
        Object type = msgMap.get("_type");
        //TODO 參數(shù)校驗
        System.out.println(" ==== userId :" + userId + ",type :" + type);
        System.out.println("aliyun send message success");
        return "aliyun send message success";
    }
}
4.3.3 添加SPI配置文件

按照前文的方式,在resources目錄下創(chuàng)建一個文件,注意文件名稱為SPI中的接口全名,文件內(nèi)容為實現(xiàn)類的全類名。

com.congge.spi.BitptImpl
4.3.4 將jar安裝到倉庫中

完成實現(xiàn)類的編碼后,通過maven命令將jar安裝到倉庫中,然后再在上一步的biz-app中引入即可。

4.4 效果演示

啟動biz-app服務,調用接口:localhost:8087/sendMsg?msg=sendMsg,可以看到如下效果。

圖片

為什么會出現(xiàn)這個效果呢?因為我們在實現(xiàn)類配置了具體使用哪一種方式進行短信的發(fā)送,而加載插件的時候正好能夠找到對應的服務實現(xiàn),這樣的話就給當前的業(yè)務提供了一個較好的擴展點。

圖片

五、寫在文末

從當前的趨勢來看,插件化機制的思想已經(jīng)遍布各種編程語言,框架,中間件,開源工具等領域,因此掌握插件化的實現(xiàn)機制對于當下做程序實現(xiàn),或架構設計方面都有著很重要的意義,值得深入研究,本篇到此結束,感謝觀看!

責任編輯:武曉燕 來源: 蘇三說技術
相關推薦

2025-07-01 09:21:33

2025-01-02 11:20:47

2023-07-10 08:44:00

2025-02-11 07:55:45

2019-08-21 14:34:41

2022-12-23 08:28:42

策略模式算法

2021-05-07 07:03:33

Spring打包工具

2017-08-02 14:44:06

Spring Boot開發(fā)注解

2021-10-18 12:04:22

Spring BootJava開發(fā)

2021-10-18 10:36:31

Spring Boot插件Jar

2018-05-25 16:32:45

Spring BootJava開發(fā)

2016-10-14 14:16:28

Spring BootJava應用

2016-11-03 09:59:38

kotlinjavaspring

2025-05-12 04:01:00

2017-03-06 15:43:33

Springboot啟動

2024-12-03 08:00:00

2025-06-06 01:00:00

Spring場景范式

2025-06-27 02:44:00

2023-10-15 22:40:25

插件JIB

2025-05-13 00:00:02

IntelliJIDEALombok
點贊
收藏

51CTO技術棧公眾號