由于,自己管理的一个部署在Tomcat的项目偶有莫名的停止的情况,导致用户无法访问,这种情况还经常发生在放假期间,当在家时,有电脑还可以远程重启下,但如果出门在外,无法远程时,就急死人了,所以就想可以自己开发一个小工具监测系统一旦停止,立即重启Tomcat服务器呢,于是说干就干.
思路是这样:在项目根目录下放一个最简单的testTom.jsp的页面,只返回一个数字1,代码如:
<%out.println("1");%>
然后,再执行:startup.bat.完成Tomcat的重启,JAVA类主要代码如下:
URL url=new URL(testUrl);
URLConnection urlCon=url.openConnection();
InputStream is=urlCon.getInputStream();
InputStreamReader isw=new InputStreamReader(is);
BufferedReader bufferedReader=new BufferedReader(isw);
try {
//获取网面内容
webContent = new StringBuffer();
String str = bufferedReader.readLine();
while (str != null) {
webContent.append(str);
str = bufferedReader.readLine();
}
}finally {
if(is!=null)
is.close();
if(isw!=null)
isw.close();
if(bufferedReader!=null)
bufferedReader.close();
}
//preValue=1,如果webContent不相等则是tomcat停止了
if(preValue!=null&&preValue.equals(webContent.toString()))
{
TomcatIsRun =true;
statusMessage=new StringBuilder("Tomcat is Run ").append(new Date().toLocaleString()).toString();
}else
{
//已判断到Tomcat停止,
TomcatIsRun =false;
statusMessage=new StringBuilder("Tomcat is shutdown ").append(new Date().toLocaleString()).toString();
long currentTime=System.currentTimeMillis();
//设定了重启间隔时间,防止频繁的重启
if((currentTime-startTime)>offsetTime)
{
//重启服务器
restartTomcat("未知原因");
startTime=currentTime;
}
}
执行tomcat的停止与重启,主要代码如:
public void restartTomcat(String message) throws IOException {
String shutdownService=tomcatHome+"/bin/shutdown.bat";
// .toString();
addTextToLogArea(shutdownService);
executeProgram(shutdownService);
String startService=tomcatHome+"/bin/startup.bat";
// .toString();
addTextToLogArea(startService);
executeProgram(startService);
String fileName="restartServerLog"+System.currentTimeMillis()+".log";
saveLog(fileName,new StringBuilder(new Date().toString())
.append(" 重启原因:").append(message).toString());
}
private void executeProgram(String filePath) throws IOException {
ExecuteProgram exp=new ExecuteProgram(filePath,this.testLogTextArea);
Thread thread=new Thread(exp);
thread.start();
}
public void run() {
try {
execute();
} catch (IOException ex) {
Logger.getLogger(ExecuteProgram.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void execute() throws IOException {
Process process;
process= Runtime.getRuntime().exec(filePath);
InputStream is = process.getInputStream();
BufferedInputStream bi = new BufferedInputStream(is);
InputStreamReader ir = new InputStreamReader(bi, "GBK");
BufferedReader br = new BufferedReader(ir);
try {
String str = "";
while (str != null) {
str = br.readLine();
addTextToLogArea(str);
}
}finally {
if(is!=null)
{
is.close();
}
if(bi!=null)
{
bi.close();
}
if(ir!=null)
{
ir.close();
}
if(br!=null)
br.close();
process.destroy();
}
}
如果有朋友想下载来试试的话,资源地址在我的资源页面下有下载,地址是:http://download.csdn.net/detail/ant_cc/9654653
代码写得比较丑,见笑了,如有建议,请留言给我,谢谢了