在做后端服务运维时,经常遇到服务器重启时,需要移动一堆后端服务。服务器故障自动重启时,通常无人通知。把springboot服务的jar包配置开机启动太有必要了,虽然不是很复杂,这里记录一下太有必要了。
- 创建jar包启动和停止脚本
注意替换,jar包名字、jdk路径、文件路径
#!/bin/bash
APP_NAME=livestock-0.0.1-SNAPSHOT
APP_PATH=/home/
export JAVA_HOME=/home/jdk1.8.0_391
export JRE_HOME=${JAVA_HOME}/jre
usage(){
echo "请输入以下内容 [start|stop]"
exit 1
}
stop(){
echo "准备关闭当前项目已存在进程"
tpid=`ps -ef|grep ${APP_NAME}.jar|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
echo "关闭进程: ${tpid}"
kill -9 $tpid
echo "关闭完成"
else
echo '项目未运行'
fi
}
start(){
stop
echo "开始启动"
rm -f ${APP_PATH}${APP_NAME}.pid
nohup ${JRE_HOME}/bin/java -jar ${APP_PATH}${APP_NAME}.jar &
echo $! > ${APP_PATH}${APP_NAME}.pid
}
case $1 in
"start")
start
;;
"stop")
stop
;;
*)
usage
;;
esac
exit 0
- 授权脚本
chmod +x /home/starter.sh
- 将jar包定义为服务
vi /lib/systemd/system/livestock.service
写入下面内容
[Unit]
Description=A Spring Boot application
After=syslog.target
[Service]
Type=forking
User=root
ExecStart=/home/starter.sh start
ExecRestart=/home/starter.sh start
ExecStop=/home/starter.sh stop
SuccessExitStatus=143
Restart=always
RestartSec=5
PrivateTmp=true
[Install]
WantedBy=multi-user.target
- 重新加载配置
systemctl daemon-reload
- 开启启动服务
systemctl enable livestock.service