Shell script to deploy Spring Boot Jar package program

Shell script to deploy the Spring Boot Jar package program, including steps such as backup, graceful shutdown and startup.

#!/bin/bash

# 应用名称
APP_NAME="myapp"

# 应用Jar包名称及路径
APP_JAR="$APP_NAME.jar"
APP_PATH="/path/to/app"

# JVM参数(根据实际情况修改)
JAVA_OPTS="-server -Xms512m -Xmx1024m"

# 进程ID文件名称及路径
PID_FILE="$APP_NAME.pid"

# 备份目录名称及路径
BACKUP_DIR="backup"
BACKUP_PATH="/path/to/backup/$BACKUP_DIR"

# 备份应用文件
echo "正在备份应用文件..."
if [ ! -d "$BACKUP_PATH" ]; then
    mkdir -p $BACKUP_PATH
fi
cp $APP_PATH/$APP_JAR $BACKUP_PATH/$APP_JAR.`date +"%Y%m%d%H%M%S"`
echo "应用文件备份完成。"

# 检查是否已经启动
if [ -f "$PID_FILE" ]; then
    PID=`cat $PID_FILE`
    ps -p $PID > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "应用已经在运行中,进程ID为:$PID"
        exit 1
    else
        echo "PID文件存在,但进程不存在!清理PID文件并启动应用......"
        rm -f $PID_FILE
    fi
fi

# 启动应用
echo "开始启动应用..."
nohup java $JAVA_OPTS -jar $APP_PATH/$APP_JAR > /dev/null 2>&1 &
PID=$!
if [ $? -eq 0 ]; then
    echo $PID > $PID_FILE
    echo "应用启动成功,进程ID为:$PID"
else
    echo "应用启动失败,请查看日志以获取更多信息。"
fi

# 优雅关闭应用
function stopApplication {
    
    
    echo "开始关闭应用..."
    PID=`cat $PID_FILE`
    kill $PID > /dev/null 2>&1
    for ((i=0; i<30; i++)); do
        ps -p $PID > /dev/null
        if [ $? -eq 0 ]; then
            echo "等待应用关闭...第 $i 秒"
            sleep 1
        else
            echo "应用关闭成功!"
            break
        fi
    done

    # 检查是否停止成功
    ps -p $PID > /dev/null
    if [ $? -eq 0 ]; then
        echo "无法正常关闭应用,进行强制关闭..."
        kill -9 $PID > /dev/null 2>&1
    fi
}

# 捕获CTRL+C信号
trap stopApplication INT

# 永远运行脚本,直到收到信号退出
while true; do
  sleep 1
done

This shell script first backups the application files, then checks to see if the application is already running, if so, outputs an error message and exits; otherwise, it starts the application and writes the process ID to the PID file. At the same time, it also sets an elegant shutdown function and a trap to capture the CTRL+C signal to handle the graceful shutdown of the application.

This shell script is just an example. It can be modified and adapted according to the actual situation.

Guess you like

Origin blog.csdn.net/m0_50758217/article/details/130369816