使用 shell 脚本打包部署 springboot 项目

背景:目前我们的非正式环境(包括TEST,PRE)都使用jenkins进行发布,但正式环境还是手动打包发布。因此为了节省发布的时间,写了一套shell脚本进行一键发布。计划后期(如果还有后期的话)将项目迁移到docker进行发布管理。

code:

#!/bin/bash
#author cl* 

CODE_DIR="codedir"
PACKAGED_NAME="packagename"
GIT_PROJECT_NAME="projectname"
GIT_BRANCH_NAME="branchname"
APP_DEPLOY_PATH="deploypath"
PROFILE="prd"
PORT=9096

#如果任何语句的执行结果不是true则应该退出
set -e

#git初始化配置,配置后,无需手动输入用户名及密码即可从指定git管理代码
function gitinit(){
  echo "start gitinit..."
  cd ~/
  touch .git-credentials
  echo "http://username:password@xxx.xxx.xxx.xxx" > .git-credentials
  git config --global credential.helper store
  #执行此句后~/.gitconfig文件多了一项[credential] helper = store
  echo "finish gitinit..."
  
}

#pull and package gitcodeResource 
function package(){
  echo "start pull git resource code..."
  rm -rf ./$CODE_DIR
  git clone  http://xxx.xxx.xxx.xxx/Card/$GIT_PROJECT_NAME.git
  cd ./$CODE_DIR
  git checkout $GIT_BRANCH_NAME
  echo "git checkout succeed ..."
  echo "starting packaging app ..."
  mvn clean package -Dmaven.test.skip=true
  echo "packaging app success ..."
}

#code deploy
function deploy(){
  cd $APP_DEPLOY_PATH
  shutdown
  echo "rename last version..."
  if [ -f $PACKAGED_NAME.jar ]
    then
      mv $PACKAGED_NAME.jar $PACKAGED_NAME'_'`date +%Y%m%d%H%M%S`.jar
  fi
  echo "copy jar..."
  cp $APP_DEPLOY_PATH/$CODE_DIR/target/$PACKAGED_NAME.jar $APP_DEPLOY_PATH
  echo "start member@"$PORT
  startup
}

#app shutdown
function shutdown(){
  PID=$(ps -ef | grep $PACKAGED_NAME.jar | grep -v grep | awk '{ print $2 }')
  if [ -z "$PID" ]
  then
    echo Application is already stopped
  else
    echo kill $PID
    kill -9 $PID
  fi
}

#app startup
function startup(){
  echo "startuping"$GIT_BRANCH_NAME"..."
  export JAVA_HOME=$JAVA_HOME
  nohup java -server -Xms512M -Xmx512M -Xss256k \
      -XX:+UseStringDeduplication \
      -XX:+HeapDumpOnOutOfMemoryError \
      -jar $PACKAGED_NAME.jar \
      --server.port=$PORT \
      --spring.profiles.active=$PROFILE \
      > /dev/null 2>&1 &
  echo "startuping success ..."
  echo "打开端口:"$PORT"..."
  firewall-cmd --zone=public --add-port=$PORT/tcp --permanent

}

#pring helpinfo
function help(){
	echo "Usage: ./onekey.sh [gitinit|package|deploy|startup|shutdown|help]"
	echo "gitinit:初始化git设置"
	echo "package:程序打包"
	echo "deploy:程序发布"
	echo "startup:程序启动"
	echo "shutdown:程序关闭"
	echo "help:打印帮助信息"
}

case "$1" in
  'gitinit')
    gitinit
    ;;
  'package')
    package
	;;
  'deploy')
    deploy
	;;
  'startup')
	startup
	;;
  'shutdown')
	shutdown
	;;
  'help')
	help
	;;
  *)
    

esac
exit 0


用法:一次运行 gitinit,package,deploy三个命令即可。当然也可以将三个命令组合成一个命令进行一键发布。

依赖环境:Maven3+,git,Java8。

本文为风林火山博客原创,转载请注明出处:www.flcoder.com
validate