Springboot启动时记录进程ID

Springboot启动时记录进程ID

1. 背景说明

springboot项目打包成可执行jar包以后,需要通过java -jar xxx.jar启动项目.启动方式对非技术人员不太友好.所以需要项目构建时,生成一个start.batstop.bat的脚本.关闭采用taskkill -F -PID命令或者 kill -9 需要知道启动的进程ID.

2. 代码实现

  • springboot启动类,添加 ApplicationPidFileWriter listeners 实现启动时记录PID
java 复制代码
// 小游戏 地心侠士
 SpringApplication appliction = new SpringApplication(AppsApplication.class);
 appliction.addListeners(new ApplicationPidFileWriter());
 appliction.run(args);

这样项目运行后,会在根目生成一个application.pid文件,记录启动的进程ID.

  • 实现关闭代码
java 复制代码
// 小游戏  地心侠士
private static void shutdown() {
File file = new File("application.pid");
try {
	FileReader fileReader = new FileReader(file);
	String pid = null;
	try (BufferedReader br = new BufferedReader(fileReader)) {
		pid = br.readLine();
	}
	if (StringUtils.isNotBlank(pid)) {
		if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
			Runtime.getRuntime().exec("taskkill -F -PID " + pid);
		} else {
			Runtime.getRuntime().exec("kill -9 " + pid);
		}
	}
} catch (IOException e) {
	if (e instanceof FileNotFoundException) {
		System.err.println("未找到文件:" + file.getAbsolutePath());
	}
	System.out.println("读取文件异常");
}
}
  • 启动类判断是关闭还是启动
java 复制代码
public static void main(String[] args) throws IOException, ClassNotFoundException {
  for (String arg : args) {
		// 如果执行jar包时,参数为shutdown,则关闭项目
  	if ("shutdown".equals(arg)) {			
  		shutdown();
  		System.exit(0);
  	}
  }
	// TOOD 小游戏 地心侠士 
}

3. 构建配置

使用 maven-assembly-plugin 插件动态生成启动脚本,在fileSets指定文件夹路径,在package时,会自动替换其中的Maven变量,插件配置如下

xml 复制代码
<build><plugins><plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
      <appendAssemblyId>false</appendAssemblyId>
      <descriptors>
          <descriptor>./package.xml</descriptor>
      </descriptors>
  </configuration>
  <executions>
      <execution>
          <id>make-assembly</id>
          <phase>package</phase>
          <goals>
              <goal>single</goal>
          </goals>
      </execution>
  </executions>
</plugin></plugins></build>

package.xml 配置中,针对脚本处理配置如下,脚本存放在 /src/scripts 目录下

xml 复制代码
<fileSets><fileSet>
	<directory>src/scripts</directory>
	<outputDirectory>/</outputDirectory>
	<filtered>true</filtered>
</fileSet></fileSets>

4. 生成启动脚本

启动脚本模板,目录存放 /src/scripts/startup.bat, 使用maven打包变量可以生成具体启动脚本

bash 复制代码
@echo off
title SpringBoot-%date%-%time%-%cd%
java -jar -Dloader.path=resources,lib,plugin ${project.artifactId}-${project.version}.jar

5. 生成关闭脚本

关闭脚本模板,目录存放 /src/scripts/shutdown.bat

bash 复制代码
java -jar -Dloader.path=resources,lib ${project.artifactId}-${project.version}.jar shutdown

6. 总结

开发项目,尽量减少操作步骤.能代码化的脚本,一定代码化,减少人为出错的可能性.

原文地址:https://mp.weixin.qq.com/s/ZPyl-j9QgP-Pc6H-9dxFPQ