如何获取 spring 引导应用程序的进程 ID

how to get process id of a spring boot application

我注意到 spring boot 在启动期间在日志中打印了进程 ID。现在我想写一个脚本来使用这个 pid 终止这个进程并再次启动应用程序。 Spring Boot 是否提供任何 api 来获取此 pid?谢谢!

Spring Boot 提供class ApplicationPidFileWriter,然后将PID 写入文件。您可以通过将其作为侦听器添加到 SpringApplication:

来激活它
SpringApplication springApplication = new SpringApplication(DemoApplication.class);
springApplication.addListeners(new ApplicationPidFileWriter());
springApplication.run(args);

ApplicationPidFileWriter 的构造函数也可以采用带有自定义文件名的字符串或 File 对象。然后您可以从该文件中读取 PID 并在您的脚本中使用它。

您可以执行 tasklist 命令列出活动进程,它们的标识符 (PID) 将出现。

您也可以将它们写入脚本中的文件:

tasklist /v txt > filename.txt

之后就可以使用脚本读取文件获取pid了

最终您将使用脚本终止进程。

来自Part V. Spring Boot Actuator: Production-ready features documentation :

In the spring-boot module, you can find two classes to create files that are often useful for process monitoring:

  • ApplicationPidFileWriter creates a file containing the application PID (by default, in the application directory with a file name of application.pid).
  • WebServerPortFileWriter creates a file (or files) containing the ports of the running web server (by default, in the application directory with a file name of application.port).

By default, these writers are not activated, but you can enable:

  • By Extending Configuration
  • Section 60.2, “Programmatically”

这是 60.1 扩展配置部分:

In the META-INF/spring.factories file, you can activate the listener(s) that writes a PID file, as shown in the following example:

org.springframework.context.ApplicationListener=\
org.springframework.boot.context.ApplicationPidFileWriter,\
org.springframework.boot.web.context.WebServerPortFileWriter

在启动时启用 pid 和端口输出。

所以这个想法很简单:在 spring 启动应用程序的 src/main/resources/META-INF 文件夹中,如果不存在,则创建一个包含先前内容的 spring.factories 文件以启用两者( pid 或端口)或使用以下命令仅启用 PID 输出:

org.springframework.context.ApplicationListener=org.springframework.boot.context.ApplicationPidFileWriter

无需使用ApplicationPidFileWriter,只需使用ApplicationPid:

SpringApplication springApplication = new SpringApplication(MyApplication.class);
springApplication.run(args);
log.info(new ApplicationPid().toString());

只需转到 /var/run/{您的应用名称}/,读取 .pid 文件中的 pid。

使用 ApplicationPidFileWriter 是 @dunni 已经提到的一种方法。

另一种方法是使用 spring 引导执行器。 actuator/env 将 return 所有环境详细信息,如端口号、PID# 和许多其他系统属性,格式为 json。

http://主机名:端口#/actuator/env

要使用这个必须首先在他的应用程序中启用和公开执行器。 步骤:

  1. 在pom中添加actuator-starter依赖
  2. 在属性文件中启用和公开所需的执行器端点。

详情请参考:https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-metrics-endpoint

System.getProperty("PID") 获取 SPRING 引导 PID。

Code

Result