编写shell脚本让springboot项目在CentOS中开机自启动

springboot项目部署在CentOS系统上时,如果遇到停电关机,公司的实施人员就得跑到甲方现场重新启动项目并测试,很是麻烦,这里探讨如何编写shell脚本控制springboot项目开机时自动启动;

不正之处,请不吝赐教!

以eureka的jar包为例子:

上传Jar包

将eureka的jar包上传至/usr/local/eureka目录下:

编写shell脚本让springboot项目在CentOS中开机自启动

编写shell启动脚本

进入/usr/local/eureka目录,执行以下命令,创建并编辑eureka.sh启动脚本:

vi eureka.sh

内容如下,其中APP_PATH为jar包所在目录, APP_NAME为jar包的位置,JAVA_JDK为jdk的安装目录,LOG_NAME为jar包启动后日志输出位置,其他地方不需要修改:

#!/bin/bash #自定义内容 APP_PATH=http://www.likecs.com/usr/local/eureka APP_NAME=http://www.likecs.com/usr/local/eureka/eureka-server-1.0.0.jar JAVA_JDK=http://www.likecs.com/usr/local/jre1.8.0_202 LOG_NAME=http://www.likecs.com/usr/local/eureka/eurekaLog.log #执行命令有误时,提示使用说明参数 usage() { echo "Usage: sh eureka.sh [start|stop|restart|status]" exit 1 } #检查程序是否已经在运行 is_exist(){ pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' ` if [ -z "${pid}" ]; then return 1 else return 0 fi } #启动服务 start(){ is_exist if [ $? -eq "0" ]; then echo "${APP_NAME} is already running. pid=${pid} ." else nohup $JAVA_JDK/bin/java -Duser.dir=$APP_PATH -jar $APP_NAME > $LOG_NAME 2>&1 & fi } #停止服务 stop(){ is_exist if [ $? -eq "0" ]; then kill -9 $pid else echo "${APP_NAME} is not running" fi } #输出服务运行状态 status(){ is_exist if [ $? -eq "0" ]; then echo "${APP_NAME} is running. Pid is ${pid}" else echo "${APP_NAME} is NOT running." fi } #重启服务 restart(){ stop start } #根据输入参数,选择执行对应的方法,不输入则执行使用说明 case "$1" in "start") start ;; "stop") stop ;; "status") status ;; "restart") restart ;; *) usage ;; esac

编写完保存并退出,执行以下命令启动eureka服务,测试启动脚本是否正常:

#故意执行不完整的命令,测试是否提示使用说明 sh eureka.sh #启动服务 sh eureka.sh start #查看服务状态 sh eureka.sh status #停止服务 sh eureka.sh stop #重启服务 sh eureka.sh restart

编写shell脚本让springboot项目在CentOS中开机自启动

测试无误后,停止服务,执行以下命令,设置eureka脚本的可执行权限:

chmod a+wrx -R eureka

执行完之后,文件名称变绿色:

编写shell脚本让springboot项目在CentOS中开机自启动

编写开机自启动配置

执行以下命令,在/usr/lib/systemd/system目录下创建并编辑eureka.service配置文件:

vi /usr/lib/systemd/system/eureka.service

内容如下:

其中ExecStart定义了启动进程时要执行的命令,ExecReload定义重启服务时要执行的命令,ExecStop定义停止进程时要执行的名称,这些命令统统指向刚刚创建并测试通过的eureka.sh启动脚本;

[Unit] Description=eureka After=network.target [Service] Type=forking ExecStart=http://www.likecs.com/usr/local/eureka/eureka.sh start ExecReload=http://www.likecs.com/usr/local/eureka/eureka.sh restart ExecStop=http://www.likecs.com/usr/local/eureka/eureka.sh stop PrivateTmp=true [Install] WantedBy=multi-user.target

编写完保存并退出,通过systemctl命令启动eureka服务,测试启动脚本是否正常:

#查看运行状态 systemctl status eureka #启动 systemctl start eureka #关闭 systemctl stop eureka #重启 systemctl restart eureka #查看配置文件内容 systemctl cat eureka

编写shell脚本让springboot项目在CentOS中开机自启动

启动完之后,默认是没有启动开机自启动的;

编写shell脚本让springboot项目在CentOS中开机自启动

通过以下命令设置开机自启动:

systemctl enable eureka

编写shell脚本让springboot项目在CentOS中开机自启动

测试完成后关闭服务器重启,模拟断电后重启服务器,查看开机后是否自动启动:

编写shell脚本让springboot项目在CentOS中开机自启动

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgjgf.html