背景:
公司有個Java項目部署在Tomcat容器中,Tomcat意外宕機後,需要及時重啓。避免在假期時出現問題,現編寫一個自動監控Tomcat狀態的腳本,若Tomcat狀態不正常,則自動重啓Tomcat.
一、Shell腳本如下:
#!/bin/sh
# function:Automatic monitoring tomcat process,down restart operation
# author:xms
# DEFINE
# Get tomcat PID
TomcatID=$(ps -ef |grep tomcat |grep -w 'apache-tomcat-7.0.81'|grep -v 'grep'|awk '{print $2}')
# tomcat startup path
StartTomcat=/usr/tomcat/apache-tomcat-7.0.81/bin/startup.sh
# tomcat cache path
#Cache=/usr/tomcat/apache-tomcat-7.0.81/work
# Definition to monitor address of the page
WebUrl=http://10.200.1.7:8080/barcode/
# output logs
GetPageInfo=/dev/null
MonitorLog=/usr/tomcat/apache-tomcat-7.0.81/tomcat_restart/TomcatMonitor.log
Monitor()
{
echo "[info]Start monitoring tomcat...[$(date +'%F %H:%M:%S')]"
if [ $TomcatID ];then
echo "[info]tomcat process ID is:$TomcatID."
# get the return status code
TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})
if [ $TomcatServiceCode -eq 200 ];then
echo "[info]The status code is $TomcatServiceCode,tomcat startup success."
else
echo "[error]Access error,The status code is $TomcatServiceCode,The error Log has output to $GetPageInfo!"
echo "[error]Tomcat restart..."
kill -9 $TomcatID # kill the original process of tomcat
sleep 3
#rm -rf $Cache # clean tomcat cache
$StartTomcat
fi
else
echo "[error]tomcat process does not exist! tomcat restarting...."
echo "[info]$StartTomcat,please wait......"
#rm -rf $Cache
$StartTomcat
fi
echo "---------------finish in:[$(date +'%F %H:%M:%S')]---------------"
}
Monitor>>$MonitorLog
1、通過ps -ef 及 grep 命令定位到對應項目的tomcat,獲取到進程ID。
2、GetPageInfo = /dev/null,無底洞,不輸出。
3、先判斷進程是否存在,不存在則直接重啓。存在則進入狀態判斷,獲取訪問請求頁的 responseCode,不等於200的話也進行重啓。
4、保存shell 名字爲monitor.sh
5、給腳本賦值權限 chmod 777 monitor.sh
二、然後在終端輸入
crontab -e
三、定位到sh腳本的路徑下,運行腳本(絕對路徑執行會有問題,因爲路徑中含有tomcat,ps -ef|grep過濾出來的PID有誤)
*/3 * * * * cd /usr/tomcat/apache-tomcat-7.0.81/tomcat_restart && ./monitor.sh