JAVA实现监测tomcat是否宕机及控制重启的方法
程序员文章站
2024-03-06 13:46:32
本文实例讲述了java实现监测tomcat是否宕机及控制重启的方法。分享给大家供大家参考。具体如下:
detector.java:
import java.ne...
本文实例讲述了java实现监测tomcat是否宕机及控制重启的方法。分享给大家供大家参考。具体如下:
detector.java:
import java.net.url; import java.net.urlconnection; import java.util.date; /** * * @author james * */ public class detector { private static void keeptomcatalive() throws nullpointerexception { string s; string t = new string("tomcat6"); boolean istomcatalive = false; java.io.bufferedreader in; system.setproperty("sun.net.client.defaultconnecttimeout", "8000"); system.setproperty("sun.net.client.defaultreadtimeout", "10000"); try { url url = new url("http://localhost:8080/test.jsp"); 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) { //accessed page successful. return; } } in.close(); } catch (exception ex) { //ex.printstacktrace(); } try { java.lang.process p = java.lang.runtime.getruntime().exec("ps -aux"); 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("/etc/init.d/tomcat6 stop"); java.io.bufferedreader in = new java.io.bufferedreader(new java.io.inputstreamreader(p.getinputstream())); string s; string t = "stopping"; 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("/etc/init.d/tomcat6 start"); java.io.bufferedreader in = new java.io.bufferedreader(new java.io.inputstreamreader(p.getinputstream())); string s; string t = "starting"; 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(); } } private static void debug(string msg){ system.out.println("debug::: "+msg); } public static void main(string[] args) { while (true) { try { debug("detect agin <"+new date()+">"); detector.keeptomcatalive(); debug("sleep..."); thread.sleep(30000); } catch (exception ex) { ex.printstacktrace(); } } } }
希望本文所述对大家的java程序设计有所帮助。