linux shell优雅停止重启springboot微服务 (含完整shell脚本)

本篇文章不介绍如何配置和如何停止springboot的配置,网上有很多,可以搜一下。

原理是通过本地localhost的http请求停止相关服务。

#此命令是一整行,我为了方便显示进行换行了。
curl -H "Content-Type:application/json" -X POST 
http://127.0.0.1:24005/actuator/shutdown
#24005是你所在服务配置的端口

下面是springboot中yml如何配置,我们这里的配置原则是服务端口号减去1000

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    shutdown:
      enabled: true
  server:
    port: 24005
    address: 127.0.0.1
    servlet:
      context-path: /

/home/service/houhou目录下,创建的houhou.war
在jenkins打包时候可以加一个名字,我这里是 houhou.war_newbuild。如果存在这个包名,那么修改名字进行启动。

#修改包名的脚本,也就是更新houhou.war这个部署包
if [ -e houhou.war_newbuild ]; then
    #备份
    mv houhou.war "houhou.war_"`date "+%Y%m%d_%H%M%S"`
    mv houhou.war_newbuild houhou.war
fi

然后查看这个服务有没有启动,如果启动了,结束她再自动那个已经更新过的houhou.war

pid=$(ps -ef | grep houhou.war | grep java | awk '{print $2}');
echo "$pid"
##如果不存在进程则启动
if [ ! -n "$pid" ]; then
    LOGFILE="./run.log"
    java -jar ./houhou.war >> "./${LOGFILE}" 2>&1 &
    echo "启动完成"
    ps -ef | grep houhou.war
fi

还有一个就是启动这个shell脚本当前目录的包,那么要切换到当前目录。

#切换到当前目录的shell脚本
DIR="$( cd "$( dirname "$0"  )" && pwd )"
cd "${DIR}"

完整的脚本实现,如下

#!/bin/bash

#停止的端口
END_PORT=28008
#包名
APP_NAME=memeda.war
BACKUP_NAME="${APP_NAME}_"`date "+%Y%m%d_%H%M%S"`
APP_NAME_NEWBUILD=${APP_NAME}_newbuild

echo "${APP_NAME}"
echo "${END_PORT}"

#优雅的shutdown,下面的两行是一条命令
curl -H "Content-Type:application/json" -X POST http://127.0.0.1:${END_PORT}/actuator/shutdown
#上面的两行是一条命令

#进入目标目录
DIR="$( cd "$( dirname "$-1"  )" && pwd )"
cd '${DIR}'

#重命名启动war包
if [ -e ${APP_NAME_NEWBUILD} ]; then
    #备份
    if [ -e ${APP_NAME} ]; then
       mv ./${APP_NAME} ./${BACKUP_NAME}   
    fi
    mv ./${APP_NAME_NEWBUILD} ./${APP_NAME}
fi

#启动项目
bash ${DIR}/start.sh
echo '启动完成'

水平原因可能存在错误,希望指正 [email protected]

猜你喜欢

转载自blog.csdn.net/Hello_Ray/article/details/84871881