脚本作用:监控运行中的tomcat内存占用大小,当内存超过所定义的最大使用内存时,自动重启tomcat,达到释放内存的效果。
脚本如下 check_tomcat.sh:
#!/bin/bash
#by Lia#check tomcat process memery.##define tomcat process, if outride the number, then restart tomcat server.
#4194305 kb = 4 G
tomcat_mem=4194304#get pids of tomcat5,tomcat6
tomcat_pid=`ps -ef | grep tomcat | grep java | awk 'NR==1 {print $2}'`echo $tomcat_pid#get tomcat5's memery(KB).
tomcat_mem=`cat /proc/$tomcat_pid/status | grep -e VmRSS | awk 'NR==1 {print $2}'`echo $tomcat_mem#tomcat env
tomcat_home=/opt/tomcat#define tomcat restart function
function restart_tomcat(){ pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'` echo $pidcd $tomcat_home/bin
if [ -n "$pid" ]
then { echo ===========shutdown================ ./shutdown.sh sleep 10 pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'` if [ -n "$pid" ] then { sleep 2 echo ========kill tomcat6============== kill -9 $pid } fi sleep 3 echo ===========startup.sh============== ./startup.sh } else echo ===========startup.sh============== ./startup.sh fi}#check log dir or not, then mkdir log dir
[ ! -d logs ] && mkdir -pv logs#if tomcat process memery outride tomcat_mem, then restart tomcat server.
if [[ $tomcat_mem -gt $tomcat_mem ]]; then echo `date "+%F %T"` [Tomcat5 RUNNING]Tomcat\'s memery is outride.>>logs/restart_tomcat_`date "+%F"`.log restart_tomcatelse echo `date "+%F %T"` [Tomcat5 RESTART]Tomcat\'s memery not outride.>>logs/restart_tomcat_`date "+%F"`.logfi
可将脚本写入crontab中,定时检测。