写项目的时候,客户有需求为jar包不能够重复启动,除了使用脚本进行限制之外,需要在程序中再加一层限制。
根本思路为,监视java全部进程,查找以启动类命名的是否有重复。
仅在测试类中通过,尚未放入项目,待更新....
测试类见下,hasAnotherProcess为主要方法,在启动类启动类中加入即可
@author 昵称输入流程——非常满意
public class Test {
public static void main(String[] args) {
if (hasAnotherProcess()) {
System.out.println("Stop");
return;
}
System.out.println("Running");
}
private static boolean hasAnotherProcess() {
String mainClassName = Thread.currentThread().getStackTrace()[1].getClassName();
Map<String, Object> map = new HashMap<>();
MonitoredHost host;
Set<Integer> vms;
try {
host = MonitoredHost.getMonitoredHost(new HostIdentifier((String)null));
vms = host.activeVms();
} catch (URISyntaxException | MonitorException e) {
throw new InternalError(e.getMessage());
}
// 轮询java进程
for (Object vmid: vms) {
if (vmid instanceof Integer) {
String name = vmid.toString();
try {
MonitoredVm mvm = host.getMonitoredVm(new VmIdentifier(name));
// 此处获得 正在轮询的 进程启动类全名
name = MonitoredVmUtil.commandLine(mvm);
mvm.detach();
} catch (Exception e) {
}
// 检查启动类是否重复
if (map.containsKey(name) && name.equals(mainClassName)) {
return true;
}
map.put(name, null);
}
}
return false;
}
}
事实上,在后续打包运行的过程之中发现了一个问题。就是使用jar包启动时,监听到的进程名称是jar包的名字,而非启动类的类名。比如我打出的包名为Test.jar,使用该包启动后,进程对应的名称也是Test.jar。
所以需要手动更改方法中的mainClassName为具体jar包名称即可,也可以自行添加配置文件进行管理。