tomcat定时重启和存活检测

           现在已经项目上线,为了保证应用能高可用,能够及时释放内存,我做了个定时的存活检测和定时重启脚本,利用linux的crontab机制,具体如下:

#1、脚本目的:
#   存活检查和定时重启,保证服务的高可用
#2、运行规则:
#该脚本在crontab里设置每隔五分钟执行一次,比如:....... 11:55 12:00 12:05 12:10 12:15 ......
#3、逻辑规则:
#检测每个tocmat进程是否存在,如果不存在就启动,如果存在该进程,就检测当前时间是否是该tomcat的重启时间,
#如果当前时间是一个app的重启时间就开始重启

export JAVA_HOME=/opt/jdk/jdk1.6.0_27
export PATH=$PATH:$JAVA_HOME/bin
BASE_HOME='/opt/tomcat/tomcat-'
clan1Time=01:40:00
login1Time=01:00:00
register1Time=01:10:00

function_checkAlive()
{
  CATALINA_HOME=$1
  TomcatID=$(ps aux |grep "$CATALINA_HOME"|grep -v grep|awk '{print $2}'|awk 'NR==1')
  echo "the tomcat-$TOMCAT_HOME id  : $TomcatID"
  if [ $TomcatID ];then  # 这里判断TOMCAT进程是否存在
        echo "[info]当前tomcat-$CATALINA_HOME进程ID为:$TomcatID..."
        function_checkIfNeedRestart $CATALINA_HOME $2
  else 
        echo "[error]tomcat-$TOMCAT_HOME进程不存在!tomcat-$TOMCAT_HOME开始自动重启..."
        function_restartApp $CATALINA_HOME
  fi
}

diff=0

date2stamp () {
    date --utc --date "$1" +%s
}

dateDiff (){
 case $1 in
    -s)   sec=1;      shift;;
    -m)   sec=60;     shift;;
    -h)   sec=3600;   shift;;
    -d)   sec=86400;  shift;;
    *)    sec=86400;;
 esac
 dte1=$(date2stamp $1)
 dte2=$(date2stamp $2)
 diffSec=$((dte2-dte1))
 if ((diffSec < 0)); then abs=-1; else abs=1; fi
   diff=$((diffSec/sec*abs))
   echo $diff
}

function_checkIfNeedRestart(){
  currentTime=`date +"%T"`
  if [ "$2" == "login1" ];then
    restartTime=$login1Time
  fi
  if [ "$2" == "clan1" ];then
    restartTime=$clan1Time
  fi
  if [ "$2" == "register1" ];then
    restartTime=$register1Time
  fi

  dateDiff -s $currentTime $restartTime

  echo "current time : $currentTime, restart time $restartTime, diff time :$diff"
  if [ $diff -gt 0 -a $diff -lt 9 ];then
     function_restartApp $1
  fi
}



function_restartApp()
{
  CATALINA_HOME=$1
  echo "restart app $CATALINA_HOME"
  cd $CATALINA_HOME
  ./bin/qs.sh
}

echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"
for APP in clan1 login1 register1 
    do
    CATALINA_HOME="$BASE_HOME$APP"
    function_checkAlive $CATALINA_HOME $APP
    echo "-----------------------------------------------"
done
exit 0;
相关文章
相关标签/搜索