知乎专栏 |
我们明白了 kill 的原理后,常常需要与 pid 打交道,使用 ps 命令是可以查看 pid 的,但是当我们运行多个实例的时候会常常搞混,所以最好的方式是让 springboot 把PID写入到文件中。
package cn.netkiller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.ApplicationPidFileWriter; @SpringBootApplication public class Application { public static void main(String[] args) { System.out.println("Starting..."); SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addListeners(new ApplicationPidFileWriter()); springApplication.run(args); } }
程序运行后会在当前目录下产生一个 PID 文件
neo@MacBook-Pro-Neo ~/workspace/microservice/test % cat application.pid 44027
修改 pid 文件位置可以配置 application.properties
server.port=8080 spring.pid.file=/tmp/spring.pid
在启动的时候指定 pid 文件位置
SpringApplication application = new SpringApplication(Application.class); application.addListeners(new ApplicationPidFileWriter("/tmp/app.pid")); application.run();
最后说说容器,容器的进程ID永远是 1 所以配置与否自己斟酌。
[root@localhost netkiller.cn]# docker exec -it spring cat /tmp/spring.pid 1