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
喜欢请赞赏一下啦^_^

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
2009-01-16 【Vegas原创】查找删除重复键的数据
2009-01-16 【Vegas原创】SQL Server 阻止了对组件 'SQL Mail XPs' 的 过程'sys.xp_sendmail' 的访问的解决方法