A Linux script for running Java SpringBoot, run.sh

  1. Automatically get the latest executable JAR and WAR based on the directory you are in
  2. Automatically execute commands using the environment variable JAVA_HOME (configurable)
  3. Support graceful logout (the default wait time is 60 seconds, configurable, if more than 60 seconds forced logout)
  4. Supports monitoring SpringBoot online status
  5. Support for adding custom running parameters (e.g., JVM parameters, SpringBoot parameters)
  6. Support common functions: start, stop, restart, view status, view logs
  7. The SpringBoot project supports viewing application port information

The directory structure is as follows

├ ─ ─ fastboot - 0.0.1. Jar# application jar├── logs │ ├─ console.log# Application console input log│ └ ─ ─ for server pid# Application PID└ ─ ─ run. Sh# execute script
Copy the code

Configurable parameters

Use 1.

Add the execute permission to a file

This command is executed for the first time
chmod +x run.sh
Copy the code

Restart and clear logs

Check the status

Start the

stop

2. Show

# grant execute permission (initialize execute once)
chmod +x run.sh 
# Start the application
sh run.sh start
# Stop the application
sh run.sh stop
# View the application
# sh run.sh status
# Restart the application
sh run.sh restart c  # add c to delete the historical log file
View the application log
sh run.sh logs
Copy the code

3. The source code (run. Sh)

#! /bin/bash
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = that start = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# 1. Grant run permission to chmod +x run.sh
# 2. Start the application: sh run.sh start
# 3. Stop the application: sh run.sh stop
# 4. View the application: sh run.sh status
Sh run. Sh restart c # add c to delete the historical log file
# 6. View application logs: sh run.sh logs
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = that end = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = the author start = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# @author: houyu
# @date: 2021-08-19
# @mail: [email protected]([email protected])
# @blog: https://www.ihouyu.cn
# @csdn: https://blog.csdn.net/JinglongSource
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = author end = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# Refresh environment variables
source /etc/profile
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = parameter start = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# ------ Java path, either JAVA_HOME or Java executable path, using environment variable JAVA_HOME by default
# JAVA = "/ usr/local/JAVA/jdk1.8.0 _281 / bin/JAVA"
# JAVA = "/ usr/local/JAVA/jdk1.8.0 _281"
JAVA="${JAVA_HOME}"
# ------ File path
DIR_PATH=`cd $(dirname $0); pwd`
# ------ service file name (default to use the latest.jar or.war file in the directory)
SERVER_FILE_NAME=`ls -t ${DIR_PATH} | egrep '\.jar|\.war' | head -1`
# ------ Java parameters
JAVA_OPT="${JAVA_OPT} -Duser.timezone=Asia/Shanghai"
JAVA_OPT="${JAVA_OPT} -Xms128m -Xmx128m"
# ------ Spring parameters
SPRING_OPT="${SPRING_OPT} --spring.profiles.active=prod"
# ------ console file
#CONSOLE_FILE="/dev/null"
CONSOLE_FILE="${DIR_PATH}/logs/console.log"
# ------ Number of seconds to wait timeout when stopping
STOP_TIMEOUT=60
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = parameter end = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = method start = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#
# service PID
_SERVER_PID=0
# service port
_SERVER_PORT=0
# log directory
_LOG_PATH="${DIR_PATH}/logs"
# second argument to input
_P2=$2
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Parse the pid of the service
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
resolve_server_pid() {
    _SERVER_PID=0
    if [ -f "${_LOG_PATH}/server.pid" ]; then
        If pid file exists, read file
        _SERVER_PID=$(cat "${_LOG_PATH}/server.pid")
        Check whether the PID really exists
        if test $(ps -ef | awk '{print $2}' | grep -w ${_SERVER_PID} | wc -l) -eq 0; then
            Failed to find pid for file record
            rm -rf ${_LOG_PATH}/ server. Pid sleep 0.2 _SERVER_PID = 0Reparse the pid of the service
            #resolve_server_pid
        fi
    #else
    If pid file does not exist, try to get pid based on application name
    # if test $(pgrep -f ${SERVER_FILE_NAME} | wc -l) -gt 0; then
    # # Indicates the application is running, using the first PID
    # _SERVER_PID=$(pgrep -f ${SERVER_FILE_NAME} | head -1)
    # else
    # _SERVER_PID=0
    # fi
    fi
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Parse the port of the service
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
retry_resolve_server_port() {
    _SERVER_PORT=0
    Parse the pid of the service
    resolve_server_pid
    # Test 5 minutes (300 seconds)
    for(( i=0; i<=300; i++ )); do
        Check whether pid exists
        if test $(ps -ef | awk '{print $2}' | grep -w ${_SERVER_PID} | wc -l) -eq 0; then
            rm -rf ${_LOG_PATH}/server.pid
            _SERVER_PID=0
            break
        fi
        Check whether the pid port is bound
        if test $(netstat -tulnp | grep "${_SERVER_PID}/" | wc -l) -gt 0; then
            _SERVER_PORT=$(netstat -tulnp | grep "${_SERVER_PID}/" | head -1 | awk '{print $4}' | awk -F ":" '{print $NF}')
            break
        fi
        [[ $i%5 -eq 0 ]] && echo "--- Observing server port using ${i}s"
        sleep 1
    done
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# start
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
start() {
    echo "----------------------------------------------------------------------------- Start [0] ------"
    Parse the pid of the service
    resolve_server_pid
    if [ "${_SERVER_PID}" -ne 0 ]; then
        # if _SERVER_PID! = 0, the application is running and not started
        echo "--- Do not start, ${SERVER_FILE_NAME} already started! [ SERVER_PID = ${_SERVER_PID}]. ""
        echo "----------------------------------------------------------------------------- Start [1] ------"
        return
    fi
    #
    echo "--- Starting ${SERVER_FILE_NAME} ..."
    If JAVA is a directory, add /bin/java
    [ -d "${JAVA}" ] && JAVA="${JAVA}/bin/java"
    # If JAVA is not an existing file, try using the default JAVA
    [ ! -e "$JAVA" ] && JAVA=`which java`
    If Java is not an existing file, empty it
    [ ! -e "$JAVA" ] && unset JAVA
    if [ -z "${JAVA}" ]; then
        echo -e "\033[31mPlease set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better!\033[0m"
        exit 1
    fi
    Determine whether the log file needs to be deleted
    if [[ "$_P2"= ="c"]].then
        If the second argument is c, delete the log file
        echo -e "--- \033[33mDeleting ${SERVER_FILE_NAME} log file(${DIR_PATH}/logs/*)\033[0m"
        rm -rf ${DIR_PATH}/logs/*
    fi
    Check the log directory
    test -d ${DIR_PATH}/logs/ || mkdir -p ${DIR_PATH}/logs/
    # execute script
    # nohup java -Xmx128m -jar /home/app/server.jar --spring.profiles.active=prod >> /home/app/logs/console.log 2>&1 & echo $! > /home/app/logs/server.pid
    #
    Run parameters
    RUN_OPT="${JAVA_OPT} -jar"
    RUN_OPT="${RUN_OPT} ${DIR_PATH}/${SERVER_FILE_NAME}"
    [ -n "${SPRING_OPT}" ] && RUN_OPT="${RUN_OPT} ${SPRING_OPT}"
    #
    echo "-- -- --$JAVA ${RUN_OPT}"
    echo "$JAVA ${RUN_OPT}" > ${CONSOLE_FILE}
    nohup $JAVA ${RUN_OPT} >> ${CONSOLE_FILE}2 > &1 &echo $! > ${_LOG_PATH}/server.pid
    #
    echo "-- -- --${SERVER_FILE_NAME} is running"
    echo -e "--- You can check the log file \033[36m${CONSOLE_FILE}\033[0m or execute the command on the next line"
    echo -e "--- \033[40;37mtail -f -n 300 ${CONSOLE_FILE}\033[0m"
    Sleep for 1 second
    sleep 1
    Parse the pid of the service
    resolve_server_pid
    Determine if the application is running successfully
    if [ "${_SERVER_PID}" -eq 0 ]; then
        echo -e "--- \033[31mStart failure ${SERVER_FILE_NAME}\033[0m"
    else
        if [ -n "${SPRING_OPT}" ]; then
            If it is a Spring project, you need to observe whether the port is successfully bound
            retry_resolve_server_port
            # 
            if [ "${_SERVER_PORT}" -eq 0 ]; then
                echo -e "--- \033[31mStart failure ${SERVER_FILE_NAME}\033[0m"
            else
                _SERVER_PORT_TEXT=`netstat -tulnp | grep "${_SERVER_PID}/" | awk 'BEGIN{ORS=" "}{print $4}'`
                echo -e "--- \033[32mStart successfully ${SERVER_FILE_NAME} [ SERVER_PID = ${_SERVER_PID}, SERVER_PORT = ${_SERVER_PORT_TEXT}]\033[0m"
            fi
        else
            echo -e "--- \033[32mStart successfully ${SERVER_FILE_NAME} [ SERVER_PID = ${_SERVER_PID}, \033[0m\033[33mSERVER_PORT = unknown \033[0m\033[32m]\033[0m"
        fi
    fi
    echo "----------------------------------------------------------------------------- Start [1] ------"
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# stop
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
stop() {
    echo "----------------------------------------------------------------------------- Stop [0] ------"
    Parse the pid of the service
    resolve_server_pid
    if [ "${_SERVER_PID}" -eq 0 ]; then
        # _SERVER_PID = 0, then the application is not running
        echo "--- Stopped ${SERVER_FILE_NAME}"
        echo "----------------------------------------------------------------------------- Stop [1] ------"
        return
    fi
    echo "--- Graceful Stopping ${SERVER_FILE_NAME} ..."
    Perform graceful shutdown
    kill- 15${_SERVER_PID}
    # Number of seconds currently waiting
    _wait_seconds=0
    #
    while true; do
        if test $(ps -ef | awk '{print $2}' | grep -w ${_SERVER_PID} | wc -l) -eq 0; then
            echo "--- Stopped ${SERVER_FILE_NAME}"
            break
        fi
        if [ "${_wait_seconds}" -ge "${STOP_TIMEOUT}" ]; then
            # Force the process to terminate
            echo -e "--- \033[31mWait timeout(${_wait_seconds}s), forced shutdown [kill -9 ${SERVER_FILE_NAME}].\033[0m"
            sudo kill9 -${_SERVER_PID}
            break
        fi
        sleep 1
        let _wait_seconds++
        echo "--- Wait ${_wait_seconds}s"
    done
    if [ $? -eq 0 ]; then
        echo "--- Stop successfully ${SERVER_FILE_NAME}"
        rm -rf ${_LOG_PATH}/server.pid
    else
        echo "--- Stop failure ${SERVER_FILE_NAME}"
    fi
    echo "----------------------------------------------------------------------------- Stop [1] ------"
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# state
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
status() {
    echo "----------------------------------------------------------------------------- status [0] ------"
    Parse the pid of the service
    resolve_server_pid
    if [ "${_SERVER_PID}" -eq 0 ]; then
        echo -e "--- \033[33mStopped $SERVER_FILE_NAME\033[0m"
    else
        _SERVER_PORT_TEXT=`netstat -tulnp | grep "${_SERVER_PID}/" | awk 'BEGIN{ORS=" "}{print $4}'`
        [ -z "$_SERVER_PORT_TEXT" ] && _SERVER_PORT_TEXT="unknown "
        echo -e "--- \033[32mRunning ${SERVER_FILE_NAME} [ SERVER_PID = ${_SERVER_PID}, SERVER_PORT = ${_SERVER_PORT_TEXT}]\033[0m"
        echo -e "--- You can check the log file \033[36m${CONSOLE_FILE}\033[0m or execute the command on the next line"
        echo -e "--- \033[40;37mtail -f -n 300 ${CONSOLE_FILE}\033[0m"
    fi
    echo "----------------------------------------------------------------------------- status [1] ------"
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# log
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
logs() {
    tail -f -n 3000 ${CONSOLE_FILE}
}
#
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = method end = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#
case "The $1" in
'start')
    start
    ;;
'stop')
    stop
    ;;
'restart')
    stop
    start
    ;;
'status')
    status
    ;;
'logs')
    logs
    ;;
*)
    echo "requires parameter [start|stop|restart|status|logs] [c]?"
    exit1;;esac
#
#
#
Copy the code

  • Public id: IT_loading
  • CSDN:blog.csdn.net/JinglongSou…
  • Blog: ihouyu. Cn /
  • E-mail: [email protected]