Linux服务器设置SpringBoot后台运行

SpringBoot项目打包后,运行脚本

#!/bin/bash
nohup java -jar\
 -Xms2g\
 -Xmx2g\
 -Dspring.profiles.active=prop\
 -Dfile.encoding=UTF-8\
 app-0.0.1.jar > app.log 2>&1 &

mvn命令直接运行

mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8081 -Dfile.encoding=UTF-8"

启动、重启、关闭脚本

#!/bin/sh

#jar名称
APP_NAME='demo-0.0.1.jar'

#=======================================================================

#当前应用进行的变量标识
APP_PID=''


# 重新获取APPID
function refAppPID(){
    APP_PID=`ps -ef|grep $APP_NAME|grep 9091|grep -v grep|grep -v kill|awk '{print $2}'`
}


# 获取运行程序的pid 进程号
function getAppPID(){
    if [ ! $APP_PID ]; then #未获取过
        refAppPID
    fi
}


# 启动
function start(){
    refAppPID #获取进程PID, 需重新获取, 避免restart时无法正确启动。

    if [ $APP_PID ]; then
        echo " [$APP_NAME] App is running.  this start fail.  "
        return 0
    fi

    nohup /usr/local/jdk1.8.0_291/bin/java -Dserver.port=9091 -Dfile.encoding=UTF-8 -Xms512m -Xmx768m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCDetails -Xloggc:./logs/gc.log -XX:MaxInlineSize=420 -jar /home/scott/service/$APP_NAME >/dev/null 2>start.log &

    echo " [$APP_NAME] App starting ... "
}

# 停止
function stop(){
    getAppPID #获取进程PID


    if [ ! $APP_PID ]; then
        echo " [$APP_NAME] App is NOT running. "
        return 0
    fi

    echo " [$APP_NAME] [pid=$APP_PID] [kill -15] stop process... "
    kill -15 $APP_PID     # kill-15 :正常退出程序

    sleep 5 #等待5s

    # 重新获取PID
    refAppPID

    #仍然存在 需要kill -9
    if [ $APP_PID ]; then
        forcekill
    fi

    echo " [$APP_NAME] Stop Success! "
}

# 检查
function check(){
    getAppPID #获取进程PID

    if [ $APP_PID ]; then
        echo " [$APP_NAME] App is running. PID:[$APP_PID] "
    else
        echo " [$APP_NAME] App is NOT running. "
    fi
}

# 强制kill进程
function forcekill(){
    getAppPID #获取进程PID

    if [ $APP_PID ]; then
        echo " [$APP_NAME] [pid=$APP_PID] [kill -9] Kill ing ... "
        kill -9 $APP_PID
        echo " [$APP_NAME] [pid=$APP_PID] [kill -9] Kill Success! "
    else
        echo " [$APP_NAME] App is NOT running. "
    fi
}

echo ''

command=$1

if [ "${command}" ==  "start" ]; then
    start

elif [ "${command}" ==  "stop" ]; then
     stop

elif [ "${command}" ==  "restart" ]; then
     stop
     start

elif [ "${command}" ==  "check" ]; then
     check

elif [ "${command}" ==  "kill" ]; then
     forcekill

else
    echo "Usage: $0 {start|stop|restart|check|kill|}"
fi

echo ''

将服务安装为systemd系统服务

将下列文本保存到/lib/systemd/system目录中

[Unit]
Description=Spring Boot App Service
After=syslog.target network.target

[Service]
Type=forking
User=scott
Group=scott
ExecStart=/home/scott/service/run.sh start
ExecReload=/home/scott/service/run.sh restart
ExecStop=/home/scott/service/run.sh stop
Restart=always
RestartSec=1

[Install]
WantedBy=multi-user.target
posted @ 2019-05-13 14:24  Bruce.Chang.Lee  阅读(452)  评论(0)    收藏  举报