spring boot 插件化开发(三)

饭恰完了,接着写。

private void addJarToClasspath(Plugin plugin) {
        try {
            File file = new File(plugin.getUrl());
            URL url = file.toURI().toURL();

            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(classLoader, url);
        } catch (IllegalAccessException | MalformedURLException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException("添加插件jar包到classpath失败,插件名称:" + plugin.getName());
        }
    }

这段代码在类com.pinyi.mian.PluginManager中。

3、spring托管

private JarFile readJarFile(Plugin plugin) {
        try {
            return new JarFile(plugin.getUrl());
        } catch (IOException e) {
            throw new RuntimeException("获取插件中的文件信息失败,插件名称:" + plugin.getName());
        }
    }
JarFile jarFile = readJarFile(plugin);
Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
private void traverseJar(Enumeration<JarEntry> jarEntryEnumeration, ConfigurableApplicationContext context,
                             Plugin plugin) {
        while (jarEntryEnumeration.hasMoreElements()) {
            JarEntry jarEntry = jarEntryEnumeration.nextElement();
            if (jarEntry.isDirectory() || !jarEntry.getName().endsWith(".class")
                    || plugin.getScanPath().stream().noneMatch(scanPath -> jarEntry.getName().startsWith(scanPath))) {
                continue;
            }

            String className = jarEntry.getName().substring(0, jarEntry.getName().length() - 6);
            className = className.replace('/', '.');

            try {
                Class c = classLoader.loadClass(className);
                BeanDefinitionRegistry definitionRegistry = (BeanDefinitionRegistry) context.getBeanFactory();
                for (Class springIOCAnnotationClass : springIOCAnnotations) {
                    if (c.getAnnotation(springIOCAnnotationClass) != null) {
                        definitionRegistry.registerBeanDefinition(className,
                                BeanDefinitionBuilder.genericBeanDefinition(c).getBeanDefinition());
                        break;
                    }
                }
            } catch (NoClassDefFoundError | ClassNotFoundException e1) {
                traverseJar(jarEntryEnumeration, context, plugin);
            }
        }
    }

上面的三段代码做了以下几件事:

1)获取jar包里的所有文件(包括目录)。

2)遍历所有的文件。

3)将路径与数据库plugin表配置的扫描路径相同的类注册到spring提供的工厂。

scanPath是可以自己指定格式并解析的,也就是可以指定多个路径,需要自己修改代码。

接下来就是注册listener了

package com.pinyi.mian.events.listeners;

import com.pinyi.mian.JDBCManager;
import com.pinyi.mian.PluginManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.net.URLClassLoader;


public class DynamicLoadingPluginListener implements SpringApplicationRunListener {

    private PluginManager pluginManager;

    public DynamicLoadingPluginListener(SpringApplication application, String[] args) {
        pluginManager = new PluginManager();
    }

    @Override
    public void starting() {

    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment configurableEnvironment) {
        JDBCManager.url = configurableEnvironment.getProperty("spring.datasource.url");
        JDBCManager.username = configurableEnvironment.getProperty("spring.datasource.username");
        JDBCManager.password = configurableEnvironment.getProperty("spring.datasource.password");

        pluginManager.setClassLoader((URLClassLoader) configurableEnvironment.getClass().getClassLoader());
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext configurableApplicationContext) {

    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext configurableApplicationContext) {
        pluginManager.register(configurableApplicationContext);
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        pluginManager.boot(context);
    }

    @Override
    public void running(ConfigurableApplicationContext context) {

    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }
}
org.springframework.boot.SpringApplicationRunListener=com.pinyi.mian.events.listeners.DynamicLoadingPluginListener

可以看到,在listener的environmentPrepared函数中,设置了classLoader,这个classLoader与spring使用的是同一个,如果你发现插件加载成功后不生效,可能就是classLoader指定错误,比如引入了下面的依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>

那么整个主程序大概就是这个样子,我没有写bootClass部分,因为实际没有用过,可以删除掉。

接下来就是插件部分。

插件

插件就很简单了,引入主程序,想怎么写就怎么写,完事儿。

1、主程序打包

使用以下插件打包:

  <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
      </configuration>
  </plugin>

install命令。

2、插件引用主程序

<dependency>
     <groupId>com.pinyi</groupId>
     <artifactId>hope</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <scope>provided</scope>
</dependency>

scope使用provided,否则插件打包后会把主程序一并打入。

接下来就是写插件代码了

我这里写了个定时任务,调用了printHello这个函数,但这个函数是定义在主程序的一个类当中,通过注入的方式引入。

package com.pinyi.plugin.devastate;

import com.pinyi.mian.example.HelloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduleTask {

    @Autowired
    private HelloWorld helloWorld;

    @Scheduled(fixedRate = 6)
    protected void printHello() {
        helloWorld.printHello();
    }
}

接下来把插件打包,配置插件表,启动主程序,就可以看到“hello world”。

--------------------------------------以下是建议----------------------------------------

这个方案有2个我认为比较严重的缺陷:

1)设计不合理,比如配置信息的读取方式。

2)技术框架的限制,比如不支持热插拔。

建议衡量一下利弊,以及对方案及代码进行修改后使用。这里仅供参考。

ps:主程序稍微改一下就能在不重启的情况下引入新的插件。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值