tomcatサービス状態を検出し、自動的に再起動できるコードです。
5086 ワード
ソース
:http://java0note.blog.51cto.com/469557/110003
:http://java0note.blog.51cto.com/469557/110003
。 。 ,
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
/**
* *
*/
public class Detector {
private static void keepTomcatAlive() throws NullPointerException {
String s;
String t = new String("tomcat5.exe");
boolean isTomcatAlive = false;
java.io.BufferedReader in;
try {
URL url = new URL("http://localhost/heartbeat.htm");
URLConnection con = url.openConnection();
in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
con.setConnectTimeout(1000);
con.setReadTimeout(4000);
while ((s = in.readLine()) != null) {
if (s.length() > 0) {
//
return;
}
}
in.close();
} catch (Exception ex) {
}
try {
java.lang.Process p = java.lang.Runtime.getRuntime().exec("tasklist");
in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
while ((s = in.readLine()) != null) {
if (s.startsWith(t)) {
isTomcatAlive = true;
break;
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
if (isTomcatAlive) {
System.out.println("<" + new Date() + "> Tomcat is alive but not response!");
stopTomcat();
}
startTomcat();
}
public static void stopTomcat() {
try {
java.lang.Process p = java.lang.Runtime.getRuntime().exec("net stop \"Apache Tomcat\"");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
String s;
String t = " ";
boolean restart = false;
while ((s = in.readLine()) != null) {
if (s.indexOf(t) != -1) {
restart = true;
break;
}
}
System.out.println("<" + new Date() + "> Tomcat is stop " + (restart ? "OK" : "ERROR"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startTomcat() {
try {
java.lang.Process p = java.lang.Runtime.getRuntime().exec("net stop \"Apache Tomcat\"");
} catch (Exception e) {
e.printStackTrace();
}
try {
java.lang.Process p = java.lang.Runtime.getRuntime().exec("net start \"Apache Tomcat\"");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
String s;
String t = " ";
boolean restart = false;
while ((s = in.readLine()) != null) {
if (s.indexOf(t) != -1) {
restart = true;
break;
}
}
System.out.println("<" + new Date() + "> Tomcat is start " + (restart ? "OK" : "ERROR"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
while (true) {
try {
Detector.keepTomcatAlive();
Thread.sleep(30000);
} catch (Exception ex) {
}
}
}
}
リモート再起動tomcat ,jsp :
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<%
Runtime run = Runtime.getRuntime();
Process pro = run.exec("d:\\tomcat\\bin\\restart.bat"); // ,linux .sh , shutdown.bat 。 , tomcat
%>
restart.bat
call shutdown.bat
delay.exe 5
call startup.bat
, , delay.exe 5, ,80
, ,restart.bat net stop Tomcat net start Tomcat !