在和小老弟闲聊时,他问我springboot项目能不能配置成linux系统服务,每次他在linux环境启动springboot程序,都要执行java -jar或nohup java -jar感觉很繁琐。当时我的直觉是当然可以,毕竟springboot是以快速开发为卖点。于是我就去官方文档搜一下,这次没有谷歌百度,直接走官网,主要是想装逼一下,没有其他原因。果然皇天不负苦心人,这么轻易就让我找到答案,答案链接如下
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#deployment
springboot官方文档提供了2种方案注册成服务
我就以软连接的形式注册成服务来演示,另外一种就留给大家自己玩
1、建立软连接
sudo ln -s /usr/local/hrm.jar /etc/init.d/hrm
这步做完,就已经注册成服务,是不是很简单。接下来就可以愉快的执行下如下命令
service hrm start
如果出现
Application is running as root (UID 0). This is considered insecure.
Started [30120]
说明基本上差不多成功了,再查看下日志,其日志存放在 /var/log/{appname}.log。形如本文的/var/log/hrm.log。如果日志也没问题,那恭喜你,服务注册成功。如果没成功,问题可能有如下几种
1、env: /etc/init.d/hrm: Permission denied
出现这种问题,可以先确认下你是不是以拥有jar文件的用户身份启动服务,如果不是,那就切换拥有该文件权限的用户来启动服务。如果你就是倔强不想切换用户,那你也可以执行类似如下命令解决
chmod 777 /usr/local/hrm.jar
这种方式有个坑点就是,你下次上传新的jar时,执行service hrm start时必须得先执行
chmod 777 /usr/local/hrm.jar
否则依然会报权限拒绝
2、Application is running as root (UID 0). This is considered insecure. Unable to find Java
出现这种问题,只要执行如下命令就可以解决
ln -s /usr/local/jdk/bin/java /sbin/java
3、不管怎么操作,都不成功
先确认下你的jar是不是可以执行的,借用官方的话
If you configured Spring Boot’s Maven or Gradle plugin to generate a fully executable jar, and you do not use a custom embeddedLaunchScript, your application can be used as an init.d service. To do so, symlink the jar to init.d to support the standard start, stop, restart, and status commands.
如果不是,则可以在你项目的pom.xml加如下内容
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
springboot项目注册成服务总体上还是比较简单,这种方式比较适合于纯单体的项目。如果是存在多项目依赖,搭配jenkins来自动集成部署,也是一个可以考虑的选择
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#deployment