Linux 中使用脚本启动 Java 服务
#!/bin/sh
# 服务启动参数
#JAVA_OPTS="-Xms512m -Xmx512m -XX:MetaspaceSize=512m -XX:MaxMetaspaceSize=1024m -XX:ParallelGCThreads=4 -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=utf-8"
JAVA_OPTS="-Xmx2g -Xms2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./"
# 服务输出的控制台日志的文件名
LOG_FILE="console.log"
# 所有类型服务的端口号
ALL_PORT=('8081' '5423' '5699' '5424' '8888' '5443' '6060' '6061')
# 目标 Java 服务端口号
JAR_PORT=""
# 指令事件
EXECUTE_EVENT=""
# 检查程序是否处于运行状态
is_exist() {
pid=`ps -aux|grep ${JAR_NAME}|grep -v grep|grep -v vi|grep -v dbx|grep -v tail|grep -v start|grep -v stop|sed -n 1p|awk '{print $2}'`
if [ -z "${pid}" ]; then
return 0
else
echo "pid is ${pid[i]}";
return 1
fi
}
# 服务运行状态查看方法
status() {
is_exist
if [ $? -eq "1" ]; then
echo "serivce is running,pid is ${pid}"
else
echo "serivce is not running!"
fi
}
# 服务停止方法
stop() {
pid=`netstat -anp|grep ${JAR_PORT}|awk '{printf $7}'|cut -d/ -f1`
if [ -z "${pid}" ]; then
echo "service is not running!"
else
echo "pid is ${pid[i]}";
echo "pid = $pid begin kill -9 $pid"
kill -9 $pid
sleep 2
echo "service process stopped!"
fi
}
# 服务启动方法
start() {
is_exist
if [ $? -eq "1" ]; then
echo "service is already running. pid is ${pid}"
else
echo "JAR_NAME: $JAR_NAME"
echo "JAVA_OPTS: $JAVA_OPTS"
echo "LOG_FILE: $LOG_FILE"
echo "spring.profiles.active: $env"
if [ -z "${JAR_NAME}" ]; then
echo "JAR_NAME is blank"
else
nohup java -jar $JAR_NAME --spring.profiles.active=$env $JAVA_OPTS>/home/$SERVICE_TYPE/$ENV_FILE/$LOG_FILE 2>&1 &
tail -800f /home/$SERVICE_TYPE/$ENV_FILE/$LOG_FILE
fi
fi
}
while getopts ":d:k:e:" optname
do
case "$optname" in
"d")
JAR_NAME=$OPTARG;
jar_name_array=(${JAR_NAME//// })
app_name=${jar_name_array[${#jar_name_array[@]}-1]}
echo "app_name is $app_name"
app_name_array=(${app_name//_/ })
app=${app_name_array[0]}
echo "app is $app"
case "$app" in
"PC")
SERVICE_TYPE="admin"
;;
"PDA")
SERVICE_TYPE="pda"
;;
*)
echo "app name is illegal characters"
exit 0
esac
EXECUTE_EVENT="start"
;;
"k")
if [ "$OPTARG" != null ];then
if [[ "${ALL_PORT[@]}" =~ "${OPTARG}" ]]; then
JAR_PORT=$OPTARG
else
echo "port $OPTARG is illegal characters"
exit 0
fi
else
echo "-k need a port param"
exit 0
fi
EXECUTE_EVENT="stop"
;;
"e")
env=$OPTARG;
case "$env" in
"dev")
ENV_FILE="dev";
;;
"test")
ENV_FILE="test";
;;
"prod-gz")
ENV_FILE="prod-gz";
;;
"prod-fs")
ENV_FILE="prod-fs";
;;
"prod-rd")
ENV_FILE="prod-rd";
;;
*)
echo "env is illegal characters"
exit 0
esac
;;
esac
done
case "$EXECUTE_EVENT" in
"start")
if [ -z "${env}" ]; then
echo "env is blank"
else
echo "About to start..."
start
fi
;;
"stop")
echo "About to stop..."
stop
;;
esac
exit 0
更多:https://cloud.tencent.com/developer/article/1780384
标签:脚本,Java,name,JAR,app,pid,echo,FILE,Linux From: https://www.cnblogs.com/duolaa/p/16870974.html