Tomcat自动监听重启.250116

1. bash脚本

vim /home/sh/restart_tomcat.sh

#!/bin/sh
# configurations:Automatic monitoring tomcat process, hung up the restart operation
# author:Amadeus
LANG="en_US.utf8"
export LANG
export PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
export JAVA_HOME=/home/java/jdk1.8.0_391

target_server="/home/tomcat"
# tomcat PPID
tomcat_server=$(ps -ef | grep ${target_server}/ | grep "org.apache.catalina.startup.Bootstrap start" | awk '{printf $2}')

# tomcat_startup
startTomcatServer=${target_server}/bin/startup.sh

# 定义要监控的页面地址
WebUrl=http://127.0.0.1:9090/heartbeat

# 输出日志
GetPageInfo=/dev/null
tomcatMonitorLog=/tmp/restart_tomcat.log
Monitor()
{
  echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"
  if [ $tomcat_server ];then
       echo "[info]tomcat_server the process ID for:$tomcat_server."
       # 获取返回状态码
       TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})
       if [ $TomcatServiceCode -ne 200 ];then
            echo "[info]Return code for $TomcatServiceCode,tomcat the server is not normal."
            ps -ef | grep $target_server/ | grep -v grep | grep -v restart_tomcat |awk '{print $2}' | xargs kill -9 
            sleep 10
            $startTomcatServer
            sleep 10
       else
            echo "[info]Return code for $TomcatServiceCode,tomcat the server is normal."
       fi
  else
        echo "[error]Process does not exist!tomcat server  Automatic restart..."
        echo "[info]$StartTomcat,Please wait for a while......"
        sleep 10
        $startTomcatServer
        sleep 10
  fi
  echo "------------------------------"
}
Monitor>>$tomcatMonitorLog

2.解释

grep -w 'apache-tomcat-5.5.23'        //-w选项搜索一个单词,并且避免搜索到词中的部分字串。 搜索含有apache-tomcat-5.5.23的行

grep -v 'grep'    //去掉含有grep的行

awk '{print $2}'  //用空格切分 取第二列

xargs kill -9 //批量删除进程

ps -ef | grep $target_server/ | grep -v grep | grep -v restart_tomcat |awk '{print $2}' | xargs kill -9   //获取tomcat的进程id 

wc -l //统一前面结果的字符串个数

但是仅仅是 tomcat进程存在是不够的,需要访问下 站点页面看看 是否访问正常 正常状态为200 通过curl

curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code}   //访问页面并保存页面内容返回状态码

-s --silent //静默模式,就是不显示错误和进度
-o $GetPageInfo //将文件保存到本地并命名为$GetPageInfo  
-m 10 //表示如果10秒内无法完成获取网页源码的操作,则放弃
--connect-timeout 10  //表示如果10秒内无法连接,则放弃
$WebUrl //就是我们要访问的页面路径变量
-w  //curl的-w参数我们可以自定义curl的输出,%{http_code}代表http状态码

如果状态码为200则 tomcat正常,否则 kill 杀掉tomcat 进程, 访问tomcat的启动脚本 start.sh 启动tomcat

3. 添加定时任务

crontab -e 每5分钟执行一次脚本进行tomcat检测

*/5 * * * * /home/sh/restart_tomcat.sh
posted @ 2025-01-16 16:48  中国的Amadeus  阅读(9)  评论(0)    收藏  举报