JAVA实现监测tomcat是否宕机及控制重启的方法
本文实例讲述了JAVA实现监测tomcat是否宕机及控制重启的方法。分享给大家供大家参考。具体如下:
Detector.java:
importjava.net.URL; importjava.net.URLConnection; importjava.util.Date; /** * *@authorjames * */ publicclassDetector{ privatestaticvoidkeepTomcatAlive()throwsNullPointerException{ Strings; Stringt=newString("tomcat6"); booleanisTomcatAlive=false; java.io.BufferedReaderin; System.setProperty("sun.net.client.defaultConnectTimeout","8000"); System.setProperty("sun.net.client.defaultReadTimeout","10000"); try{ URLurl=newURL("http://localhost:8080/test.jsp"); URLConnectioncon=url.openConnection(); in=newjava.io.BufferedReader(newjava.io.InputStreamReader(con.getInputStream())); con.setConnectTimeout(1000); con.setReadTimeout(4000); while((s=in.readLine())!=null){ if(s.length()>0){ //accessedpagesuccessful. return; } } in.close(); }catch(Exceptionex){ //ex.printStackTrace(); } try{ java.lang.Processp=java.lang.Runtime.getRuntime().exec("ps-aux"); in=newjava.io.BufferedReader(newjava.io.InputStreamReader(p.getInputStream())); while((s=in.readLine())!=null){ if(s.startsWith(t)){ isTomcatAlive=true; break; } } in.close(); }catch(Exceptione){ e.printStackTrace(); } if(isTomcatAlive){ System.out.println("<"+newDate()+">Tomcatisalivebutnotresponse!"); stopTomcat(); } startTomcat(); } publicstaticvoidstopTomcat(){ try{ java.lang.Processp=java.lang.Runtime.getRuntime().exec("/etc/init.d/tomcat6stop"); java.io.BufferedReaderin=newjava.io.BufferedReader(newjava.io.InputStreamReader(p.getInputStream())); Strings; Stringt="Stopping"; booleanrestart=false; while((s=in.readLine())!=null){ if(s.indexOf(t)!=-1){ restart=true; break; } } System.out.println("<"+newDate()+">Tomcatisstop"+(restart?"OK":"ERROR")); }catch(Exceptione){ e.printStackTrace(); } } publicstaticvoidstartTomcat(){ try{ java.lang.Processp=java.lang.Runtime.getRuntime().exec("/etc/init.d/tomcat6start"); java.io.BufferedReaderin=newjava.io.BufferedReader(newjava.io.InputStreamReader(p.getInputStream())); Strings; Stringt="Starting"; booleanrestart=false; while((s=in.readLine())!=null){ if(s.indexOf(t)!=-1){ restart=true; break; } } System.out.println("<"+newDate()+">Tomcatisstart"+(restart?"OK":"ERROR")); }catch(Exceptione){ e.printStackTrace(); } } privatestaticvoiddebug(Stringmsg){ System.out.println("Debug:::"+msg); } publicstaticvoidmain(String[]args){ while(true){ try{ debug("Detectagin<"+newDate()+">"); Detector.keepTomcatAlive(); debug("Sleep..."); Thread.sleep(30000); }catch(Exceptionex){ ex.printStackTrace(); } } } }
希望本文所述对大家的java程序设计有所帮助。