java守护进程启动和关闭脚本

时间:2021-05-20 14:53:36
# 程序名称
PROJECT_NAME=route

#程序路径
APP_HOME=$(dirname $(pwd))/$PROJECT_NAME

#java库目录
JAVA_LIB_PATH=$APP_HOME/resource/daemon/lib

#JAVA_HOME
JAVA_HOME=/home/software/jdk1.8


#依赖路径,route.jar中使用mf文件指定依赖jar包,否则就需要指定所有jar包
CLASS_PATH=$APP_HOME/resource/daemon/route.jar
#CLASS_PATH=$CLASS_PATH:$JAVA_LIB_PATH/netty-all-4.1.17.Final.jar
#CLASS_PATH=$CLASS_PATH:$JAVA_LIB_PATH/disruptor-3.2.1.jar
#CLASS_PATH=$CLASS_PATH:$JAVA_LIB_PATH/log4j-api-2.0.2.jar
#CLASS_PATH=$CLASS_PATH:$JAVA_LIB_PATH/log4j-core-2.0.2.jar


#参数
JAVA_OPTS=-Xms512m -Xmx512m -Xnoclassgc -Xverify:none

#程序入口类
MAIN_CLASS=com.dice.game.StartupWrapper

#程序ID文件
PID_FILE=${APP_HOME}/${PROJECT_NAME}.pid


#日志输出路径
LOG_FILE=${APP_HOME}/logs/${PROJECT_NAME}.out


#判断文件是否存在,如果不存在则创建
if [ ! -f "$PID_FILE" ]; then  
  touch "$PID_FILE"  
    echo 0 > $PID_FILE
fi

if [ ! -f "$LOG_FILE" ]; then
  touch "$LOG_FILE"
fi 


#输出
echo "service name: $PROJECT_NAME"
echo "app home: $APP_HOME"
echo "java home: $JAVA_HOME"
echo "class path: $CLASS_PATH"
echo "main class: $MAIN_CLASS"
echo "pid file : $PID_FILE"

pid=0

#获得pid
getpid() {
   pid=`cat $PID_FILE`
}

#启动项目
start() {
   getpid

   if [ $pid -ne 0 ]; then
      echo "================================"
      echo "warn: already started! or bad close last time!"
      echo "================================"
   fi

    echo -n "Starting..."
    nohup $JAVA_HOME/bin/java -server $JAVA_OPTS -classpath $CLASS_PATH $MAIN_CLASS >> $LOG_FILE 2>&1 & echo $! > $PID_FILE
    getpid
    if [ $pid -ne 0 ]; then
     echo "================================="
         echo "[Start Success] (pid=$pid)"
     echo "================================"
    else
     echo "================================="
         echo "[Start Failed]"
     echo "================================="
    fi
}

#关闭项目
#使用 kill -15 pid 方式来关闭进程,使得程序可以执行shutdownhook释放资源
stop() {
    getpid

    if [ $pid -ne 0 ]; then
      skill -15 $pid
      echo "================================"
      echo "stoping"
      echo "================================"
   fi
}


##脚本入口
case "$1" in
   'start')
      start
      ;;
   'stop')
     stop
     ;;
  *)
     echo "Usage: $0 {start|stop}"
     exit 1
esac
exit 0