创建一个管理Java服务的shell脚本
2024-11-19
创建脚本 run.sh:
#!/bin/bash
APP_NAME=/opt/apps/app.jar
DEFAULT_JAVA_OPTS="-server \
-Xms1024m \
-Xmx1024m \
-Dfile.encoding=utf-8 \
-Duser.timezone=GMT+08 \
-Dspring.profiles.active=test"
JAVA_OPTS=${JAVA_OPTS:-$DEFAULT_JAVA_OPTS}
usage() {
echo "Usage: sh run.sh [start|stop|restart|status]"
exit 1
}
is_exist(){
pid=$(ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}')
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
start(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running. pid=${pid} ."
else
java $JAVA_OPTS -jar ./$APP_NAME
fi
}
stop(){
is_exist
if [ $? -eq "0" ]; then
kill -9 $pid
else
echo "${APP_NAME} is not running"
fi
}
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
restart(){
stop
start
}
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac
赋予执行权限
chmod +x run.sh
执行脚本
sh run.sh start