Spring Boot jar 启动时设置环境参数



1 摘要

通常在使用 Spring Boot 开发项目时需要设置多环境(测试环境与生产环境等),但是项目打包却只能指定一种环境,有没有一种办法,能够只打一个 jar 包,但是启动的时候指定项目环境?作者经过在网上查阅资料并测试,发现这一功能可以实现,这就大大方便了项目的部署工作(可以实现多环境自动部署)。

2 核心代码

2.1 spring Boot 多环境配置

../demo-web/src/main/resources/application.yml
## spring config
spring:
  # environment: dev|test|pro
  profiles:
    active: dev

2.2 spring Boot 项目启动命令

Linux 命令行后台启动 spring boot jar:

nohup java -jar xxx.jar --spring.profiles.active=test > /dev/null 2>&1 &

根据不同的部署环境修改 --spring.profiles.active 值即可

3 Spring boot 简易启动与停止 shell 脚本

3.1 启动脚本

../doc/script/start-springboot.sh
#!/bin/sh
# 
# 启动 jar 运行


# 项目部署目录
projectDir=/opt/springboot/
# 项目运行 jar 名称
jarName="springbootdemo.jar"
# 脚本日志目录
logDir=/var/log/springbootdemo/
# 项目部署环境
profileActive=dev

# 这里的-x 参数判断${logDir}是否存在并且是否具有可执行权限 
if [ ! -x "${logDir}" ]; then 
  mkdir -p "${logDir}" 
fi 

# 判断项目SpringBoot程序是否运行
count=$(ps -ef |grep ${jarName} |grep -v "grep" |wc -l)
if [ ${count} -lt 1 ]; then
    cd ${projectDir}
    nohup java -jar ${jarName} --spring.profiles.active=${profileActive} > /dev/null 2>&1 &
    echo "$(date '+%Y-%m-%d %H:%M:%S') 启动 ${jarName} 程序 ... ..." >> ${logDir}$(date "+%Y-%m-%d").log    
else
    echo "$(date '+%Y-%m-%d %H:%M:%S') ${jarName} 程序运行正常 !!! !!!" >> ${logDir}$(date "+%Y-%m-%d").log
fi

3.2 停止脚本

../doc/script/stop-springboot.sh
#!/bin/sh
# 
# 停止 jar 运行


# 项目部署目录
projectDir="/opt/springboot/"
# 项目运行 jar 名称
jarName="springbootdemo.jar"
# 脚本名称
scriptName="stop-springboot.sh"


# 判断项目SpringBoot程序是否运行
count=$(ps -ef |grep ${jarName} |grep -v "grep" |wc -l)
if [ ${count} -gt 0 ]; then
    echo "已经存在 ${count}${jarName} 程序在运行"
    # 获取正在运行的程序进程 id(排除 grep 本身、awk 命令以及脚本本身)
    jarPid=$(ps x | grep ${jarName} | grep -v grep | grep -v '${scriptName}' | awk '{print $1}')
    # 停止正在运行的项目进程 
    kill -9 ${jarPid}
    output=`echo "正在关闭${jarName}程序,进程id: ${jarPid}"`
    echo ${output}
    
else
    echo '没有对应的程序在运行'
fi

# 删除  jar 包
rm -rf ${projectDir}${jarName}
# 进入 项目部署目录
cd ${projectDir}

3.3 监控 Spring Boot 项目

生产环境中如果因为各种原因从而导致项目停止运行,则此时服务器便不能对外提供服务,为了保证服务能够在无人值守的时间段内持续提供服务,实现项目的自动 修复/重启 显得尤为重要。在这里,使用一种简单粗暴的方式,项目挂掉,直接重启,通过使用定时任务执行启动脚本即可。

定时任务 crontab 简单使用,以 centOS 7 为例:

开机启动定时任务服务

systemctl enable cornd

启动定时任务

systemctl start cornd

关闭定时任务服务

systemctl stop crond

添加、编辑定时任务

crontab -e

内容如下:

00,10,20,30,40,50 * * * * /root/script/start-xxx.sh

当前定时任务意思为每 10 分钟执行一次同步脚本

cron 表达式说明:

* * * * * command(s)
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

在线生成 cron : http://cron.qqe2.com/
注意事项 : */5 * * * * 表示每 5 分钟执行一次,但是可能会在部分系统中不执行

4 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章