Springboot项目jar启动停止shell脚本

系统开机启动可参考《Linux下部署springboot项目jar包开机自启

以下脚本,包含功能

  1. 启动程序时根据项目启动日志判断是否启动成功
  2. 停止程序时查询进程是否存活来判断停止成功
  3. 指定端口号启动jar
  4. 指定字符集,时区,环境启动jar
#!/bin/sh
# kconfig: 2345 85 15
# description: auto_run_jar
# author: admin

export JAVA_HOME=/usr/local/java/jdk1.8.0_231
export JRE_HOME=$JAVA_HOME/jre

# 程序名
RUN_NAME="springboot-demo.jar"

# jar位置
JAVA_OPTS=/opt/jar/springboot-demo.jar
LOG_OPTS=/opt/log/springboot-demo/springboot-demo.log

# 启动方法
start() {
    # 启动程序
    echo "$(date "+%Y-%m-%d %H:%M:%S") starting $RUN_NAME ........."
    nohup $JRE_HOME/bin/java -jar -Dfile.encoding=UTF-8 -Dserver.port=8080 -Duser.timezone=GMT+08 -Dspring.profiles.active=pro -Xms1024M -Xmx1024M -Xmn384M $JAVA_OPTS >$LOG_OPTS 2>&1 &

    # 查询日志检测java程序是否启动成功
    echo "$(date "+%Y-%m-%d %H:%M:%S") checking if started ..."
    while [ -f $LOG_OPTS ]
    do
        current=`date +%Y-%m-%d\ %H:%M`
        result=`grep "$current" $LOG_OPTS | grep "Started SpringbootDemoApplication"`
        if [[ "$result" != "" ]]
        then
            echo "$(date "+%Y-%m-%d %H:%M:%S") springboot start ..."
            break
        else
            echo "$(date "+%Y-%m-%d %H:%M:%S") waiting for start..."
            sleep 5s
        fi
    done

    echo "$(date "+%Y-%m-%d %H:%M:%S") $RUN_NAME started success."
}

# 停止方法
stop() {
    echo "$(date "+%Y-%m-%d %H:%M:%S") stopping $RUN_NAME ........."

    ID=`ps -ef | grep "$RUN_NAME" | grep -v "$0" | grep -v "grep" | grep -v stop| awk '{print $2}'`
    echo "start kill pid: $ID..."
    for id in $ID
    do
    kill $id
    echo "killed $id"
    done

    # 查看程序是否已停止
    echo "$(date "+%Y-%m-%d %H:%M:%S") checking if stopped ..."
    while true
    do
        count=`ps -ef | grep "$RUN_NAME" | grep -v "grep"`
        if [ "$?" != "0" ]
        then
        # 程序已停止
        echo "$(date "+%Y-%m-%d %H:%M:%S") $RUN_NAME stopped success."
        break
        else
        # 程序仍在运行
        echo "$(date "+%Y-%m-%d %H:%M:%S") > waiting for stop..."
        fi
        sleep 5s
    done
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo "Userage: $0 {start|stop|restart}"
        exit 1
esac

以上已通过自测。

Logo

更多推荐