Example implementation of the Tomcat monitoring script

  • 2020-06-03 08:57:56
  • OfStack

Implementation effect

The Tomcat monitoring script is used to detect whether the Tomcat application is normal according to a fixed time frequency. If the process does not exist, start Tomcat. If a process exists and access is abnormal, kill the process and start Tomcat again.

The body of the script


vi /home/dev/ctl/tomcat-inspector/image.sh
#!/bin/bash
echo $(date '+%Y-%m-%d %H:%M:%S')
whoami
JAVA_HOME=/opt/java/jdk1.8.0_40
PATH=$JAVA_HOME/bin:$PATH
export PATH JAVA_HOME
port=8086
sn="tomcat-image-$port"
th="/home/dev/tomcat/$sn"
url="http://you-app-server/"
tomcat=`ps -ef | grep java | grep $sn | grep $port | wc -l`
if [ $tomcat -eq 0 ]
then
  echo $sn stoped.
  echo starting $sn ......
  $th/bin/startup.sh
fi
if [ $tomcat -ge 1 ]
then
  tpid=`ps -ef | grep java | grep $sn | grep $port | awk '{print $2}'`
  echo $sn is running, pid = $tpid
  httpStatus=`curl -I $url 2>/dev/null | grep HTTP | awk '{print $2}'`
  echo $httpStatus
  if [[ -z "$httpStatus" || $httpStatus -ge 500 ]]
  then
    echo killing $sn ......
    kill -9 $tpid
    echo starting $sn ......
    $th/bin/startup.sh
  fi
fi

Set the execution frequency


crontab -e
*/5 * * * * /home/dev/ctl/tomcat-inspector/image.sh >> /home/dev/ctl/tomcat-inspector/logs/image.log 2>&1

conclusion


Related articles: