很久之前,我写过一个脚本用于重启Spring Boot应用,但最近在看Spring Boot文档,发现之前写的的确不够优雅
Spring Boot 文档中,有一大章专门写关于如何在系统中部署,其中,个人认为最佳的方案是作为一个systemd服务运行,由Liunx服务直接调度
编译一个可执行的Jar
首先,我们需于改变我们的Jar,能在Linux系统中直接运行
在Maven中,添加executable配置为true
1 2 3 4 5 6 7
| <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration> </plugin>
|
或者,如果你使用的是Gradle,添加launchScript()
1 2 3
| bootJar { launchScript() }
|
注意:可执行的Jar由于嵌入了脚本,所以无法通过jar -xf命令解压
创建systemd服务
在/etc/systemd/system文件下,创建myapp.service(假设你的服务名叫做myapp,请依据实际情况修改)
1 2 3 4 5 6 7 8 9 10 11
| [Unit] Description=myapp After=syslog.target
[Service] # User=myapp ExecStart=/var/myapp/myapp.jar SuccessExitStatus=143
[Install] WantedBy=multi-user.target
|
上传Jar
我们需要上传并将生成的可执行Jar,放在与myapp.service中ExecStart相同的位置
运行systemd服务
当我们完成上面步骤,就可以直接通过systemctl来运行或控制Spring Boot应用
1 2 3 4 5 6 7 8 9 10 11 12
| systemctl enable myapp.service
systemctl disable myapp.service
systemctl start myapp.service
systemctl stop myapp.service
systemctl restart myapp.service
systemctl status myapp.service
|
这是不是比用pgrep pgrep java -jar之类的简单方便多了