用shell脚本制作一个java服务启动器
⚠️ 不足之处请多多包涵 ,转载请注明出处。
如果在运行中提示lsof
命令不存在, 请使用yum install lsof
命令安装
#! /bin/bash
## author: wzc
## e-mail: voisen@icloud.com
## This is a project launcher
# 启动/停止 超时时间 秒
WAIT_TIMEOUT=60
# 启动的项目数组
PROJECTS=(YOUR_JAR_1.jar YOUR_JAR_2.jar)
#jar 运行额外的参数
JAR_ARGS=""
function stop_project()
{
if [ $1 == '全部' ]
then
for P in ${PROJECTS[@]}
do
stop $P
done
else
stop $1
fi
}
function start_project()
{
if [ $1 == '全部' ]
then
for P in ${PROJECTS[@]}
do
start $P
done
else
start $1
fi
}
function service_pid()
{
echo `ps -ef | grep $1 | grep "java -jar" | awk {'print $2'}`
}
function listen_port_pid()
{
echo `lsof -p $1 | grep "$2"`
}
function stop()
{
RESULT=`service_pid $1`
if [[ -n $RESULT ]]
then
kill -15 $RESULT
TIMEOUT=$(($WAIT_TIMEOUT * 10))
while [ $TIMEOUT -gt 0 ]
do
RESULT=`service_pid $1`
W_IDX=$(($TIMEOUT % 4))
printf "> 停止服务 [%s]......[%s]\r" $1 ${WAIT_CHARS[$W_IDX]}
if [ -z $RESULT ]
then
printf "> 停止服务成功 [%s]......[v]\n" $1
return
fi
sleep 0.1s
TIMEOUT=$(( $TIMEOUT - 1 ))
done
printf "> 停止服务超时 [%s]......[×]\n" $1
return
fi
printf "> 服务未运行 [%s]......[!]\n" $1
}
function start()
{
# 检查服务是否在运行
RESULT=`service_pid $1`
if [[ -n $RESULT ]]
then
printf "> 服务正在运行 [%s]......[!]\n" $1
return
fi
nohup java -jar $JAR_ARGS $1 >/dev/null 2>&1 &
TIMEOUT=$(($WAIT_TIMEOUT * 10))
while [ $TIMEOUT -gt 0 ]
do
W_IDX=$(($TIMEOUT % 4))
printf "> 启动服务 [%s]......[%s]\r" $1 ${WAIT_CHARS[$W_IDX]}
RESULT=`service_pid $1`
if [[ -n $RESULT ]]
then
LRESULT=`listen_port_pid ${RESULT[0]} $1`
fi
if [[ -n $LRESULT ]]
then
printf "> 启动服务成功 [%s]......[v]\n" $1
return
fi
sleep 0.1s
TIMEOUT=$(( $TIMEOUT - 1 ))
done
printf "> 启动服务超时 [%s]......[x]\n" $1
}
WAIT_CHARS=('|' '/' '-' '\')
echo "**** 目标项目 ****"
echo '[0]全部'
for((i=0;i<${#PROJECTS[@]};i++));
do
echo '['$((i+1))']'${PROJECTS[$i]}
done
echo ""
echo -n "请选择项目: "
read idx
echo ""
if [ $idx -gt ${#PROJECTS[@]} ]
then
echo " ❗️ 输入的项目无效[$idx]"
exit
fi
if [ $idx == 0 ]
then
NAME='全部'
else
NAME=${PROJECTS[$((idx-1))]}
fi
echo "***** 执行的操作 *****"
echo "[1]启动 [$NAME]"
echo "[2]停止 [$NAME]"
echo "[3]重启 [$NAME]"
echo ""
echo -n "请选择对[$NAME]的操作: "
read OPS
echo ""
case $OPS in
1)
# 启动项目
start_project $NAME
;;
2)
stop_project $NAME
;;
3)
stop_project $NAME
start_project $NAME
;;
*) echo " ❗️ 无效的操作"
;;
esac