547 字
3 分钟
用 Bash 管理 Spring Boot 应用

此脚本用于 Linux,按完整 JAR 路径识别 Java 进程。

#!/bin/bash
#替换 JAR 文件名,按需填写外部配置文件
APP_NAME=app.jar
CONFIG_NAME=application.yml
APP_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || exit 1
cd -- "$APP_DIR" || exit 1
APP_PATH="$APP_DIR/$APP_NAME"
#使用说明,用来提示输入参数
usage() {
echo "Usage: bash 执行脚本.sh [start|stop|restart|status]"
exit 1
}
#检查程序是否在运行
is_exist(){
pid=""
local app_cmdline argument previous first app_pid
for app_cmdline in /proc/[0-9]*/cmdline; do
[ -r "$app_cmdline" ] || continue
previous=""
first=1
while IFS= read -r -d '' argument; do
if [ "$first" -eq 1 ]; then
case "${argument##*/}" in java) ;; *) break ;; esac
first=0
fi
if [ "$previous" = "-jar" ] && [ "$argument" = "$APP_PATH" ]; then
app_pid="${app_cmdline#/proc/}"
pid="${app_pid%/cmdline}"
return 0
fi
previous="$argument"
done < "$app_cmdline"
done
return 1
}
#启动方法
start(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running. pid=${pid} ."
else
config_param=()
[ -n "$CONFIG_NAME" ] && config_param=("-Dspring.config.location=$CONFIG_NAME")
nohup java "${config_param[@]}" -jar "$APP_PATH" > log.file 2>&1 &
sleep 1
if is_exist; then
echo "${APP_NAME} started. pid=${pid} ."
else
echo "${APP_NAME} failed to start. Check log.file ." >&2
return 1
fi
fi
}
#停止方法
stop(){
if is_exist; then
local stopping_pid="$pid"
kill -TERM "$stopping_pid" || return 1
local waited=0
while is_exist && [ "$pid" = "$stopping_pid" ]; do
if [ "$waited" -ge 30 ]; then
echo "${APP_NAME} did not stop within 30 seconds." >&2
return 1
fi
sleep 1
waited=$((waited+1))
done
echo "${APP_NAME} stopped."
else
echo "${APP_NAME} is not running"
fi
}
#输出运行状态
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
#重启
restart(){
stop && start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac

APP_NAME: jar包名

CONFIG_NAME:外挂配置文件名(非必填)

CONFIG_NAME为空则不会添加指定配置文件的启动参数

使用方法:

control.sh放入和jar包配置文件同一目录下

bash control.sh start

其他操作分别为 stop、restart、status。

脚本和 JAR、配置文件放在同一目录,脚本会自动进入该目录。CONFIG_NAME 留空时使用应用默认的配置查找方式;指定 spring.config.location 时会替换默认配置位置。

输出保存在 log.file,可以用 tail -f log.file 查看。status 只检查进程,应用是否启动成功还要看日志。

stop 发送 TERM 后等待进程退出,30 秒未退出则返回失败;restart 只在停止成功后启动。

用 Bash 管理 Spring Boot 应用
https://www.klzy.me/posts/31/
作者
快乐之源
发布于
2024-09-29
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类

换条路线

从其他文章中稳定抽取

最后更新于 ,距今已过 794 天

部分内容可能已过时