您的位置:首页 > 运维架构

WEB应用监控与自动重启的程序和脚本

2007-07-18 10:18 417 查看
首先是在root用户的crontab中添加如下一行:

*/5 * * * * /xxx/xxx/monitorM2U.sh

即每5分钟执行一下脚本/xxx/xxx/monitorM2U.sh,这个脚本的内容是:

cd /xxx/xxx/xxx/classes;
nohup “${JAVA_HOME}”/bin/java –cp ".:${CLASSPATH} " com.mdcchina.m2u.monitor.ResponseMonitor &

其中com.mdcchina.m2u.monitor.ResponseMonitor的代码是:

/*
* Created on 2005-9-8
*
*/
package com.mdcchina.m2u.monitor;

import java.io.IOException;
import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

/**
* @author Hao Wei 监控m2u进程是否能够访问,如果不能就重启之
*/
public class ResponseMonitor {

public static void main(String[] args) {
if (!new ResponseMonitor()
. canRequest ("http://www.m2u.cn/albumshare/benber")) { //用来监控的地址
log("FATAL ERROR!!!!!!!!!!!!!/nM2U cannot be visit, it will be restarted!");
/**
* 在此可加入发送短信报警或记录失败日志的代码
**/
try {
String script = "/xxx/xxx/restart_tomcat.sh";
Process proc = Runtime.getRuntime().exec("/bin/sh " + script); //调用脚本进行重启
log("execute: " + script);
log(""+proc.waitFor());
log("===========M2U process was restarted!====== ======");
} catch (IOException e) {
log("M2U cannot be restart!!!!!!!!!!!!/n" + e.getStackTrace());
}
catch( InterruptedException e1){
log("M2U cannot be restart!!!!!!!!!!!!/n" + e1.getStackTrace());
}
} else {
log("M2U OK!");
}
}

private static void log(Object obj) {
System.out.println("::::MONITOR::::|" + new Date() + "|" + obj);
}

public boolean canRequest(String url) {
boolean success = false;
HttpClient client = null;
GetMethod getMethod = null;
try {
client = new HttpClient();
log("<<<< begin send http request to " + url);

getMethod = new GetMethod(url);
client.setConnectionTimeout(40 * 1000);
client.setTimeout(40 * 1000);
client.setHttpConnectionFactoryTimeout(40 * 1000);
client.executeMethod(getMethod);
log("response code : " + getMethod.getStatusCode());
if (getMethod.getStatusCode() < 300) {
success = true;
}
} catch (IOException ex) {
log("ERROR/n" + ex.getStackTrace());
success = false;
} finally {
try {
if (getMethod != null) {
getMethod.releaseConnection();
}
} catch (Exception ex2) {
}
try {
if (client != null) {
client.endSession();
}
} catch (Exception ex1) {
}
client = null;
}
log("<<<< end send http request to " + url);
return success;
}
}

其中,这个java程序调用的重启tomcat的脚本/xxx/xxx/restart_tomcat.sh内容如下:

/xxx/xxx/get_tomcat_pid.sh | while read PID
do
kill -9 "${PID}" &
done
su - mytt -c "cd ${CATALINA_HOME}/bin; ./startup.sh"

其中,找到tomcat主进程号的脚本/xxx/xxx/get_tomcat_pid.sh内容如下:

ps -efww|grep tomcat | while read PROCESS
do
PID2=`echo "${PROCESS}" | awk '{printf ("%s/n",$3)}'`
if [ "${PID2}" == "1" ]; then
PID1=`echo "${PROCESS}" | awk '{printf ("%s/n",$2)}'`
echo "${PID1}"
else
continue
fi
done

完鸟。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: