一. 背景
通过脚本启动 Java 服务。
二. 脚本
1. 启动 Java 服务
#!/bin/bash
nohup java -jar myservice.jar &
echo '启动完成'
最简单的启动脚本这样就可以了,启动命令就是直接 ./start.sh
( ps:需要先执行chmod +x start.sh
给脚本添加可执行权限)。
2. 加入服务名称
#!/bin/bash
jarPath=$1 # 加入 jar 路径配置
nohup java -jar $jarPath &
echo 'myservice 服务启动完成'
通过 ./start.sh ./myservice.jar
命令启动,这样就可以用同一个脚本启动不同的 jar 包。
3. 加入启动命令
#!/bin/bash
res='执行失败'
cmd=$1 # 启动命令
jarPath=$2 # jar 包路径
jarPath=`echo $jarPath | awk -F "/" '{print $NF}' `
if [ "$cmd" == 'restart' ] # 如果重启,则先找到对应的 jar 进程,kill 掉
then
pid=`ps -ef | grep "$jarPath" | grep -v 'grep\|start.sh\|ps -ef' | awk '{print $2}' `
kill -9 $pid
res='重启成功'
echo $pid
#nohup java -jar $jarPath --spring.profiles.active=dev &
elif [ "$cmd" == 'start' ] # 如果启动,则不需要kill
then
#nohup java -jar $jarPath --spring.profiles.active=dev &
res='启动成功'
fi
echo $res
现在通过 ./start.sh <start/restart> myservice.jar
命令就可以启动或重启不同 jar 包了。
4. 加入环境配置
#!/bin/bash
res='执行失败'
cmd=$1
jarPath=$2
active=$3
jarPath=`echo $jarPath | awk -F "/" '{print $NF}' `
if [ "$cmd" == 'restart' ]
then
pid=`ps -ef | grep "$jarPath" | grep -v 'grep\|start.sh\|ps -ef' | awk '{print $2}' `
kill -9 $pid
res='重启成功'
echo $pid
#nohup java -jar $jarPath --spring.profiles.active=$active & # 加入环境配置
elif [ "$cmd" == 'start' ]
then
nohup java -jar $jarPath --spring.profiles.active=$active &
res='启动成功'
fi
echo $res
现在只要通过 ./start.sh start myservice.jar prod
就能使用 prod 环境的配置启动 jar 了。
5. 加入参数校验
#!/bin/bash
res='执行失败'
cmd=$1
jarPath=$2
active=$3
if [ -z $jarPath ] # 加入简单的 jar 判断
then
echo '参数jarPath不能为空'
exit 0
fi
jarPath=`echo $jarPath | awk -F "/" '{print $NF}' `
if [ -z $active ] # 加入默认 dev 配置环境
then
active='dev'
fi
if [ "$cmd" == 'restart' ]
then
pid=`ps -ef | grep "$jarPath" | grep -v 'grep\|start.sh\|ps -ef' | awk '{print $2}' `
kill -9 $pid
res='重启成功'
echo $pid
nohup java -jar $jarPath --spring.profiles.active=$active &
elif [ "$cmd" == 'start' ]
then
nohup java -jar $jarPath --spring.profiles.active=$active &
res='启动成功'
echo $active
fi
echo $res
三. 小结
当然,我们还可以加入更多了命令,更加完整的参数校验,更多的启动命令配置。