#!/bin/bash
### java程序管理脚本
### 功能:启动、停止、重启、查看状态、查看日志
### 根据网上脚本改编而成。
###
### author : star
### date: 2019-12-30
#JDK所在路径
#JAVA_HOME="/home/dcenter/jdk1.8.0_91/bin/java"
#Java程序所在的目录(classes的上一级目录)
APP_HOME=$(dirname $(cd "$(dirname "$0")"; pwd))
cd ${APP_HOME}
# 日志写入位置
LOG_HOME="${APP_HOME}/logs"
LOG_FILE="poseidon-emos.log"
# 应用名
APP_NAME="poseidon-business-emos-server"
# jar包名称
JAR_NAME="poseidon-business-emos-server-1.0.0.jar"
# 拼凑完整的路径
APP="${APP_HOME}/${JAR_NAME}"
## 判断日志目录是否存在,不存在则创建
if [ ! -d $LOGS_DIR ]; then
mkdir $LOGS_DIR
fi
#java虚拟机启动参数
JAVA_OPTS=" -Dfile.encoding=UTF8 -Duser.timezone=GMT+08 -Xms4096M -Xmx4096M -Djava.awt.headless=true "
#JAVA_OPTS=" -ms512m -mx512m -Xmn256m -Djava.awt.headless=true -XX:MaxPermSize=128m"
JAR=$APP
prog=$APP_NAME
psid=0
## 加载环境变量
source /etc/profile
source ~/.bash_profile
## 检查pid
checkpid() {
javaps=`jps -l | grep $APP`
if [ -n "$javaps" ]; then
psid=`echo $javaps | awk '{print $1}'`
else
psid=0
fi
}
## 启动程序
start() {
checkpid
addCron
if [ $psid -ne 0 ]; then
echo "================================"
echo "warn: $APP_NAME already started! (pid=$psid)"
echo "================================"
else
echo -n "Starting $APP_NAME ..."
# nohup java -jar $JAVA_OPTS $APP >$LOG_HOME/$LOG_FILE 2>&1 &
nohup java -jar $JAVA_OPTS $APP >/dev/null 2>&1 &
checkpid
if [ $psid -ne 0 ]; then
echo "(pid=$psid) [OK]"
else
echo "[Failed]"
fi
fi
}
## 停止程序
stop() {
checkpid
delCron
if [ $psid -ne 0 ]; then
echo -n "Stopping $APP_NAME ...(pid=$psid) "
kill -9 $psid
if [ $? -eq 0 ]; then
echo "[OK]"
else
echo "[Failed]"
fi
checkpid
if [ $psid -ne 0 ]; then
stop
fi
else
echo "================================"
echo "warn: $APP_NAME is not running"
echo "================================"
fi
}
## 重启程序
restart() {
checkpid
if [ $psid -ne 0 ]; then
# echo "$APP_NAME is running! (pid=$psid)"
stop
start
else
# echo "$APP_NAME is not running"
start
fi
}
## 查看程序状态
status() {
pid=$(ps -ef | grep $JAR | grep -v 'grep ' | awk '{print $2}')
if [ -e $pid ];then
echo -e $"$prog hasn't run\t\t[OK]"
else
echo -e $"$prog is running\t\t[OK]"
fi
}
## 查询程序日志
log() {
tail -111f $LOG_HOME/$LOG_FILE
}
## 将启动脚本加入crontab(每分钟执行一次),防止程序挂掉
addCron() {
crontab=`crontab -l|grep $APP_HOME`
if [ -n "$crontab" ];then
echo "app crontab alrelady exist"
else
crontab -l > /tmp/${USER}crontab && echo "0 * * * * $APP_HOME/bin/app.sh start" >> /tmp/${USER}crontab && crontab /tmp/${USER}crontab && rm -f /tmp/${USER}crontab
echo -e "add crontab\t\t[OK]"
fi
}
delCron() {
crontab -l > /tmp/${USER}crontab |grep -v "$APP_NAME" >> /tmp/${USER}crontab && crontab /tmp/${USER}crontab && rm -f /tmp/${USER}crontab
echo -e "add crontab\t\t[OK]"
}
if [ -z "$*" ]; then
echo -e "Usage: $0 {start|stop|status|restart|log|addCron}"
else
for order in $*
do
case "$order" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
log)
log
;;
addCron)
addCron
delCron)
delCron
;;
*)
echo -e "Usage: $0 {start|stop|status|restart|log|addCron|delCron}"
exit 2
esac
done
fi
网友评论