spring boot jar项目启停脚本

之前部署形式基本参照其他开源软件的项目结构(bin,config,lib,log...),使用到maven-assembly插件,但是在开发过程免不了加上jar、更新jar版本,部署的时候很容易忘记,此次采用fatjar的方式,直接用的spring-boot-maven-plugin打包。

使用到的启停脚本:

#!/bin/bash

## This is the script for your-app service

## └── your-app
##     ├── your-app.jar(fatjar)
##     └── config
##         ├── application.yml
##         ├── application-dev.yml
##         ├── application-test.yml
##         ├── application-prod.yml
##     └── your-app.sh

# <change this param for your own jar>
JAR_NAME="your-app.jar"
CURRENT_DIR=$(cd $(dirname $0) || exit; pwd)
APP_PATH=$CURRENT_DIR/$JAR_NAME

JAVA_HOME="/usr/local/software/jdk1.8.0_231/bin"
#JAVA_OPTS=""
JAVA_OPTS="-server -Xmx1024m -Xms512m -XX:+HeapDumpOnOutOfMemoryError"

SPRING_PROFILES_ACTIVE="$2"
ENV_VARIABLES="-Djava.awt.headless=true -Dspring.profiles.active=${SPRING_PROFILES_ACTIVE:-dev}"

LOG_DIR="/var/logs/${JAR_NAME%.*}"
PROGRAM_ARGS="--log.path=${LOG_DIR}";

help() {
  echo -e "Usage: sh $0 start|stop [dev:default|test|prod]"
}

if [ ! -d "$LOG_DIR" ];then
  mkdir -p "$LOG_DIR"
fi

case $1 in
start)
  # check service
  PID=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}')
  if [ -n "$PID" ]; then
    echo -e "ERROR: The $JAR_NAME already started and the PID is ${PID}."
    exit 1
  fi
  echo "Starting the $JAR_NAME..."
  # start
  nohup $JAVA_HOME/java ${JAVA_OPTS} ${ENV_VARIABLES} -jar ${APP_PATH} ${PROGRAM_ARGS} > /dev/null 2>&1 &
  COUNT=0
  while [ $COUNT -lt 1 ]; do
    sleep 1
    COUNT=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}' | wc -l)
  done
  PID=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}')
  echo "${JAR_NAME} Started and the PID is ${PID}."
  echo "You can check the log file in ${LOG_DIR} for details."
  ;;

stop)
  PID=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}')
  if [ -z "$PID" ]; then
    echo "ERROR: The $JAR_NAME does not started!"
    exit 1
  fi
  echo -e "Stopping the $JAR_NAME..."
  # stop
  for ID in $PID; do
    kill "$ID" > /dev/null 2>&1
  done
  for ID in $PID; do
    COUNT=$(ps --no-heading -p "$ID" | wc -l)
    while [ "$COUNT" -ne 0 ]; do
      sleep 1
      COUNT=$(ps --no-heading -p "$ID" | wc -l)
    done
  done
  echo -e "${JAR_NAME} Stopped and the PID is ${PID}."
  ;;
*)
  help
  ;;
esac

1)把yml配置文件拿了出来,为的是修改配置文件时,不用再重新fatjar;在使用nacos、consul等配置中心时更易于维护

2)nohup时,将输出定位到/dev/null,是为了避免输出日志到同一文件日积月累过大而不得不做日志切割,只需要保留配置日志路径log.path下的日志(滚动生成)即可

 

posted on 2022-07-02 16:27  -赶鸭子上架-  阅读(214)  评论(0编辑  收藏  举报