CentOS7 系统 springboot应用启动脚本

最近在部署Springboot应用时,需要设置启动脚本,编写调试完成,记之如下:

启动脚本:

#!/bin/bash
APP_NAME=dataservice-engine
JAR_NAME=dataservice-engine-0.0.1-SNAPSHOT.jar
PID=$APP_NAME\.pid
PROJ_HOME=$(pwd)
# jar包路径
APP_HOME=$PROJ_HOME
LOG_PATH=$PROJ_HOME/logs
# 创建log路径
if [ ! -d $LOG_PATH ]; then
  mkdir $LOG_PATH
fi
# GC日志参数
GC_LOG_OPTS=" -XX:+PrintGC -XX:+PrintGCDetails -Xloggc:$LOG_PATH/gc-%t.log"
# GC收集器参数
GC_OPTS="-XX:+UseConcMarkSweepGC"
# JVM 启动参数
JVM_OPTIONS="-server -Xms1024m -Xmx1024m -Xmn256m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xss256k -XX:SurvivorRatio=8 $GC_OPTS $GC_LOG_OPTS "
# 使用说明,用来提示输入参数
usage() {
  echo "Usage: dataservice-engine.sh [start|stop|restart|status]"
  echo "start:       start dataservice engine service"
  echo "stop:        stop dataservice engine service"
  echo "status:      show dataservice engine state"
  echo "restart:     restart dataservice engine service"
  exit 1
}
# 检查程序是否在运行
is_exist() {
  pid=$(ps -ef | grep $APP_HOME/$JAR_NAME | grep -v grep | awk '{print $2}')
  #如果不存在返回1,存在返回0
  if [ -z "${pid}" ]; then
    return 1
  else
    return 0
  fi
}
# 启动方法
start() {
  is_exist
  if [ $? -eq "0" ]; then
    echo "WARN: $APP_NAME is already running PID=${pid}"
  else
    echo "JVM_OPTIONS : "
    echo $JVM_OPTIONS | sed 's/ /\n/g '
    nohup java -jar $JVM_OPTIONS $APP_HOME/$JAR_NAME >>$LOG_PATH/stdout.log 2>&1 &
    echo $! >$PID
    echo "INFO: start $APP_NAME successed PID=$!"
  fi
}
# 停止方法
stop() {
  #is_exist
  pidf=$(cat $PID)
  echo "INFO: app PID = $pidf begin kill $pidf"
  kill "$pidf"
  rm -rf $PID
  sleep 2
  is_exist
  if [ $? -eq "0" ]; then
    echo "INFO: app 2 PID = ${pid} begin kill -9 ${pid}"
    echo "INFO: Stopping $APP_NAME ..."
    kill -9 ${pid}
    sleep 2
    echo "INFO: $APP_NAME process stopped ---"
  else
    echo "INFO: $APP_NAME is not running ---"
  fi
}
# 输出运行状态
status() {
  is_exist
  if [ $? -eq "0" ]; then
    echo "INFO: $APP_NAME is running PID is $pid"
  else
    echo "WARN: $APP_NAME is not running"
  fi
}
# 重启
restart() {
  stop
  start
}

case "$1" in
"start")
  start
  ;;
"stop")
  stop
  ;;
"status")
  status
  ;;
"restart")
  restart
  ;;
*)
  usage
  ;;
esac
exit 0

借助上面的脚本文件,将启动应用加入 systemctl 中:

创建 dataservice-engine.service文件:

[Unit]
Description=dataservice-engine
After=network.target
[Service]
Type=forking
User=root

WorkingDirectory=/usr/local/dataservice-engine

ExecStart=/bin/bash /usr/local/dataservice-engine/dataservice-engine.sh start
ExecStop=/bin/bash /usr/local/dataservice-engine/dataservice-engine.sh stop
Restart=on-failure
[Install]
WantedBy=multi-user.target

将dataservice-engine.service文件,移动至 /etc/systemd/system/ 路径下,执行以下命令,就可以将服务添加至systemctl 管理:

  #  chmod 754 dataservice-engine,service  

posted @ 2021-09-29 15:02  Aiden郭祥跃  阅读(93)  评论(0编辑  收藏  举报
";