默认情况下 Spring Boot 应用程序打包出来都是一个可直接运行的 jar 文件,我们需要使用 java -jar *.jar 的方式去运行 Spring Boot 程序,如果我们还需要指定多个参数呢,每次都输入这些参数容易出错,也很麻烦!
本文将介绍怎样通过提供的一个启动脚本和一个停止脚本来快捷的启动和停止 spring boot 应用,这岂不是非常方便。
思路:Spring Boot 启动成功后将程序的进程ID写入到 application.pid 文件中,停止程序时根据 PID 去关闭程序即可。
假如我们的 app 为 demoApp,则目录结构如下:
demoApp
+ jre1.8.0_171
+ config
- application.yml
- application-dev.yml
- application-prod.yml
- application-test.yml
- demoApp-v1.0.0.jar
- start.bat
- stop.bat可以在 Spring Boot 启动之前添加 Listener 的方式,使用 Spring Boot 内置的 ApplicationPidFileWriter 监听器就可以自动在当前目录创建 application.pid 文件。
完整代码:
package com.hxstrive.demo;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.context.annotation.ComponentScan;
@EnableRabbit
@SpringBootApplication
@ComponentScan(basePackages = {"com.hxstrive"})
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication .class);
// 添加监听器,程序启动成功后自动在当前目录生成 application.pid 文件
// 该文件中保存的是当前程序的进程ID,我们可以根据该进程ID结束程序
application.addListeners(new ApplicationPidFileWriter());
// 启动项目
application.run(args);
}
}创建一个 start.bat 脚本,内容如下:
@echo off
setlocal
set baseDir=%~dp0
%baseDir%/jre1.8.0_171/bin/java.exe -Xbootclasspath/a:%baseDir%\config -jar %baseDir%/demoApp-v1.0.0.jar
pause创建一个 stop.bat 脚本,内容如下:
@echo off
setlocal
set basePath=%~dp0
if not "%my_home%" == "" goto gotHome
set "my_home=%basePath%\.."
:gotHome
if not exist %basePath%\application.pid (
echo not found application.pid
goto end
)
set /p pid=<%basePath%\application.pid
taskkill /f /pid %pid%
echo success shutdown server.
del %basePath%\application.pid /q
:end
pause