Spring Boot 如何实现插件化开发模式
共 14935字,需浏览 30分钟
·
2023-06-20 09:42
阅读本文大概需要 20 分钟。
来自:blog.csdn.net/zhangcongyi420/article/details/131139599
一、前言
1.1 使用插件的好处
1.1.1 模块解耦
1.1.2 提升扩展性和开放性
1.1.3 方便第三方接入
1.2 插件化常用实现思路
spi机制; 约定配置和目录,利用反射配合实现; springboot中的Factories机制; java agent(探针)技术; spring内置扩展点; 第三方插件包,例如:spring-plugin-core; spring aop技术;
二、Java常用插件实现方案
2.1 serviceloader方式
2.1.1 java spi
2.1.2 java spi 简单案例
public interface MessagePlugin {
public String sendMsg(Map msgMap);
}
public class AliyunMsg implements MessagePlugin {
@Override
public String sendMsg(Map msgMap) {
System.out.println("aliyun sendMsg");
return "aliyun sendMsg";
}
}
public class TencentMsg implements MessagePlugin {
@Override
public String sendMsg(Map msgMap) {
System.out.println("tencent sendMsg");
return "tencent sendMsg";
}
}
public static void main(String[] args) {
ServiceLoaderserviceLoader = ServiceLoader.load(MessagePlugin.class);
Iteratoriterator = serviceLoader.iterator();
Map map = new HashMap();
while (iterator.hasNext()){
MessagePlugin messagePlugin = iterator.next();
messagePlugin.sendMsg(map);
}
}
2.2 自定义配置约定方式
A应用定义接口; B,C,D等其他应用定义服务实现; B,C,D应用实现后达成SDK的jar; A应用引用SDK或者将SDK放到某个可以读取到的目录下; A应用读取并解析SDK中的实现类;
2.2.1 添加配置文件
server :
port : 8081
impl:
name : com.congge.plugins.spi.MessagePlugin
clazz :
- com.congge.plugins.impl.TencentMsg
- com.congge.plugins.impl.AliyunMsg
2.2.2 自定义配置文件加载类
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("impl")
@ToString
public class ClassImpl {
@Getter
@Setter
String name;
@Getter
@Setter
String[] clazz;
}
2.2.3 自定义测试接口
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
public class SendMsgController {
@Autowired
ClassImpl classImpl;
//localhost:8081/sendMsg
@GetMapping("/sendMsg")
public String sendMsg() throws Exception{
for (int i=0;iClass 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
,在控制台中可以看到下面的输出信息,即通过这种方式也可以实现类似serviceloader的方式,不过在实际使用时,可以结合配置参数进行灵活的控制;2.3 自定义配置读取依赖jar的方式
应用A定义服务接口; 应用B,C,D等实现接口(或者在应用内部实现相同的接口); 应用B,C,D打成jar,放到应用A约定的读取目录下; 应用A加载约定目录下的jar,通过反射加载目标方法;
2.3.1 创建约定目录
2.3.2 新增读取jar的工具类
@Component
public class 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;
//执行反射相关的方法
//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;
}
}else if(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);
//执行方法
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();
return new File(path).getParent();
}
}
2.3.3 添加测试接口
@GetMapping("/sendMsgV2")
public String index() throws Exception {
String result = serviceLoaderUtils.doExecuteMethod();
return result;
}
三、SpringBoot中的插件化实现
spring.factories
的实现;3.1 Spring Boot中的SPI机制
META-INF/spring.factories
文件中配置接口的实现类名称,然后在程序中读取这些配置文件并实例化,这种自定义的SPI机制是Spring Boot Starter实现的基础。3.2 Spring Factories实现原理
SpringFactoriesLoader
类,这个类实现了检索META-INF/spring.factories
文件,并获取指定接口的配置的功能。在这个类中定义了两个对外的方法:loadFactories 根据接口类获取其实现类的实例,这个方法返回的是对象列表; loadFactoryNames 根据接口获取其接口类的名称,这个方法返回的是类名的列表;
spring.factories
文件,并解析得到类名列表,具体代码如下:public static List
loadFactoryNames(Class> factoryClass, ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
try {
Enumerationurls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
Listresult = new ArrayList ();
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) {
throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
spring.factories
文件,就是说我们可以在自己的jar中配置spring.factories
文件,不会影响到其它地方的配置,也不会被别人的配置覆盖。spring.factories
的是通过Properties解析得到的,所以我们在写文件中的内容都是安装下面这种方式配置的:com.xxx.interface=com.xxx.classname
3.3 Spring Factories案例实现
3.3.1 定义一个服务接口
public interface SmsPlugin {
public void sendMessage(String message);
}
3.3.2 定义2个服务实现
public class BizSmsImpl implements SmsPlugin {
@Override
public void sendMessage(String message) {
System.out.println("this is BizSmsImpl sendMessage..." + message);
}
}
public class SystemSmsImpl implements SmsPlugin {
@Override
public void sendMessage(String message) {
System.out.println("this is SystemSmsImpl sendMessage..." + message);
}
}
3.3.3 添加spring.factories文件
META-INF
的目录,然后在该目录下定义一个spring.factories
的配置文件,内容如下,其实就是配置了服务接口,以及两个实现类的全类名的路径;com.congge.plugin.spi.SmsPlugin=\
com.congge.plugin.impl.SystemSmsImpl,\
com.congge.plugin.impl.BizSmsImpl
3.3.4 添加自定义接口
SpringFactoriesLoader
去加载服务;@GetMapping("/sendMsgV3")
public String sendMsgV3(String msg) throws Exception{
ListsmsServices= SpringFactoriesLoader.loadFactories(SmsPlugin.class, null);
for(SmsPlugin smsService : smsServices){
smsService.sendMessage(msg);
}
return "success";
}
localhost:8087/sendMsgV3?msg=hello
,通过控制台,可以看到,这种方式能够正确获取到系统中可用的服务实现;四、插件化机制案例实战
4.1 案例背景
3个微服务模块,在A模块中有个插件化的接口; 在A模块中的某个接口,需要调用插件化的服务实现进行短信发送; 可以通过配置文件配置参数指定具体的哪一种方式发送短信; 如果没有加载到任何插件,将走A模块在默认的发短信实现;
4.1.1 模块结构
4.1.2 整体实现思路
biz-pp定义服务接口,并提供出去jar被其他实现工程依赖; bitpt与miz-pt依赖biz-pp的jar并实现SPI中的方法; bitpt与miz-pt按照API规范实现完成后,打成jar包,或者安装到仓库中; biz-pp在pom中依赖bitpt与miz-pt的jar,或者通过启动加载的方式即可得到具体某个实现;
4.2 biz-pp 关键代码实现过程
4.2.1 添加服务接口
public interface MessagePlugin {
public String sendMsg(Map msgMap);
}
4.2.2 打成jar包并安装到仓库
4.2.3 自定义服务加载工具类
import com.congge.plugin.spi.MessagePlugin;
import com.congge.spi.BitptImpl;
import com.congge.spi.MizptImpl;
import java.util.*;
public class PluginFactory {
public void installPlugin(){
Map context = new LinkedHashMap();
context.put("_userId","");
context.put("_version","1.0");
context.put("_type","sms");
ServiceLoaderserviceLoader = ServiceLoader.load(MessagePlugin.class);
Iteratoriterator = serviceLoader.iterator();
while (iterator.hasNext()){
MessagePlugin messagePlugin = iterator.next();
messagePlugin.sendMsg(context);
}
}
public static MessagePlugin getTargetPlugin(String type){
ServiceLoaderserviceLoader = ServiceLoader.load(MessagePlugin.class);
Iteratoriterator = serviceLoader.iterator();
ListmessagePlugins = 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
public class 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 接口实现
@Service
public class 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 添加服务依赖
org.springframework.boot
spring-boot-starter-web
com.congge
biz-pt
1.0-SNAPSHOT
com.congge
miz-pt
1.0-SNAPSHOT
org.projectlombok
lombok
4.3 bizpt 关键代码实现过程
4.3.1 添加对biz-app的jar的依赖
com.congge
biz-app
1.0-SNAPSHOT
4.3.2 添加MessagePlugin接口的实现
public class BitptImpl implements MessagePlugin {
@Override
public String sendMsg(Map msgMap) {
Object userId = msgMap.get("userId");
Object type = msgMap.get("_type");
//TODO 参数校验
System.out.println(" ==== userId :" + userId + ",type :" + type);
System.out.println("aliyun send message success");
return "aliyun send message success";
}
}
4.3.3 添加SPI配置文件
com.congge.spi.BitptImpl
4.3.4 将jar安装到仓库中
4.4 效果演示
localhost:8087/sendMsg?msg=sendMsg
,可以看到如下效果五、写在文末
推荐阅读:
互联网初中高级大厂面试题(9个G) 内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper......等技术栈!
⬇戳阅读原文领取! 朕已阅