插件开发

package com.gtafe.iti;


import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


import com.gtafe.iti.domain.Plugin;
import com.gtafe.iti.plugin.PluginManager;
import com.gtafe.iti.plugin.PluginService;
import com.gtafe.iti.utils.XmlPaser;




/**
 * 主程序入口
 * @author yonghao.zheng
 *
 */
public class MasterMain {
//插件生产的数据缓存队列
private static BlockingQueue<String> dataCacheQueues = new LinkedBlockingQueue<>();

    public static void main( String[] args ){
    //配置文件路径作为主函数入参
    String prefix = System.getProperty("user.dir");
    String pluginFileName = prefix + "\\config\\plugin.xml";
    String dspMqFileName = prefix + "\\config\\DSP-MQ.xml";
    if (args.length > 0) {
    pluginFileName = args[0];
    }
    if(args.length > 1) {
    dspMqFileName = args[1];
    }
   
    final String dmfn = dspMqFileName;
    try {
List<Plugin> pluginList = XmlPaser.getPluginList(pluginFileName);
final PluginManager pluginManager = new PluginManager(pluginList);
//插件并行执行
pluginList.parallelStream().forEach(p -> {
PluginService pluginService = pluginManager.getInstance(p.getClassName());
// 调用插件
if(pluginService != null) {
pluginService.service(dmfn);
}
});
} catch (Exception e) {
e.printStackTrace();
}
    }
}





package com.gtafe.iti.plugin;



import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;


import com.gtafe.iti.domain.Plugin;


/**
 * 插件管理类,加载插件,提供获取插件实例方法
 * @author yonghao.zheng
 *
 */
public class PluginManager {
private URLClassLoader urlClassLoader;


public PluginManager(List<Plugin> plugins) throws MalformedURLException {
init(plugins);
}

private void init(List<Plugin> plugins) throws MalformedURLException {
int size = plugins.size();
URL[] urls = new URL[size];

for(int i = 0; i < size; i++) {
Plugin plugin = plugins.get(i);
String filePath = plugin.getJar();


urls[i] = new URL("file:" + filePath);
}
// 将jar文件组成数组,来创建一个URLClassLoader
urlClassLoader = new URLClassLoader(urls);
}

public PluginService getInstance(String className)  {
// 插件实例化对象,插件都是实现PluginService接口
Class<?> clazz = null;
Object instance = null;
try {
clazz = urlClassLoader.loadClass(className);
instance = clazz.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (PluginService)instance;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值