使用方式
./run.sh start
./run.sh stop
./run.sh restart
./run.sh status
#!/bin/bash
JAVA_CMD="java"
APP_NAME="bid"
JAR_NAME="bid.jar"
PROFILE="develop"
BASE_PATH=`cd $(dirname $0); pwd`
# 应用基础目录下的 env 文件中定义的变量
# source ${BASE_PATH}/env
OPTIONS="-XX:MetaspaceSize=256M"
OPTIONS="${OPTIONS} -jar ${BASE_PATH}/${JAR_NAME}"
OPTIONS="${OPTIONS} --spring.profiles.active=${PROFILE}"
echoRed() { echo $'\e[0;31m'"$1"$'\e[0m'; }
echoCyan() { echo $'\e[0;36m'"$1"$'\e[0m'; }
echoYellow() { echo $'\e[0;33m'"$1"$'\e[0m'; }
[[ -z "$stopWaitTime" ]] && stopWaitTime=10
getPid() {
pid=`ps ax | grep -i ${JAR_NAME} | grep java | grep -v grep | awk '{print $1}'`
}
start() {
getPid
if [ -z ${pid} ] ; then
doStart
else
echoCyan "[${APP_NAME}] 正在运行 ($pid)"
exit 1
fi
}
doStart() {
echoCyan "${JAVA_CMD} ${OPTIONS}"
# nohup ${JAVA_CMD} ${OPTIONS} > ${BASE_PATH}/start.out/dev/null 2>&1 &
nohup ${JAVA_CMD} ${OPTIONS} > /dev/null 2>&1 &
# 等待启动
startCounter=0 # 记录等待次数
while [ -z ${pid} ]
do
sleep 1
startCounter=`expr $startCounter + 1`
echoCyan "[${APP_NAME}] 启动中, ${startCounter} 秒 ..."
getPid
if [ "$startCounter" -ge $stopWaitTime ];then
pid=""
fi
done
# 输出启动结果
if [ -z ${pid} ] ; then
echoRed "[${APP_NAME}] 启动失败"
else
echoCyan "[${APP_NAME}] 已启动 ($pid)"
fi
}
restart() {
stop && start
}
stop() {
getPid
#是否在运行
if [ -z ${pid} ] ; then
echoYellow "[${APP_NAME}] 未在运行"
exit 0;
fi
#停止服务
echoCyan "[${APP_NAME}] 正在运行 (${pid})"
kill ${pid} #&
#等待kill没有效果,去掉
#kpid=$!
#wait $kpid
#等待停止
stopCounter=0
getPid
while [ ${pid} ] ; do
sleep 1
stopCounter=`expr $stopCounter + 1`
echoCyan "[${APP_NAME}] 停止中, ${stopCounter} 秒 ..."
getPid
if [ "$stopCounter" -ge $stopWaitTime ];then
echoCyan "[${APP_NAME}] 强制停止 ..."
kill -9 ${pid}
fi
done
#输出结果
getPid
if [ -z ${pid} ] ; then
echoCyan "[${APP_NAME}] 已停止"
else
echoRed "[${APP_NAME}] 停止失败"
fi
}
status() {
getPid
if [ -z ${pid} ] ; then
echoYellow "[${APP_NAME}] 未在运行"
exit 0
else
echoCyan "[${APP_NAME}] 正在运行 ($pid)"
exit 0
fi
}
case "$1" in
'start')
start
;;
'stop')
stop
;;
'restart')
stop
start
;;
'status')
status
;;
*)
echo "Usage: $0 { start | stop | restart | status }"
exit 1
;;
esac
exit 0