闲着没事,写着玩
package bin;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
public class PortListen implements Runnable{
public static void main(String[] args) {
//可以作为参数传递
//要监控的端口
String port="61616";
//如果要开启这个端口需要使用的命令
String cmd = "/app/apache-activemq-5.5.0/activemq-61616/bin/activemq-61616 start";
Thread t = new Thread(new PortListen(port,cmd));
t.start();
}
public PortListen(String port,String cmd){
this.port = Integer.parseInt(port);
this.cmd = cmd;
}
private int port;
private String cmd;
@Override
public void run(){
log("=================================");
log("listen is running .....");
log("listen port : "+port);
log("open port cmd : "+cmd);
log("=================================");
while(true){
try {
//如果端口关闭了,那么就出现问题了
if(isClosed(port)){
log("["+new Date()+"] The port "+port+" status is closed ,willl use the cmd to start it.");
exec(port,cmd);
log("["+new Date()+"] The port "+port+" status is start OK.");
}
Thread.currentThread().sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private boolean isClosed(int port){
boolean res = false;
Socket socket = null;
try {
socket = new Socket("localhost",port);
res = socket.isClosed();
} catch (UnknownHostException e) {
//本机操作,不会出现此异常
} catch (IOException e) {
//如果端口关闭则出现此异常
res = true;
}finally{
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
log("socket close exception : "+e.getMessage());
}
}
}
return res;
}
private int exec(int port,String cmd) throws InterruptedException, IOException{
Runtime rc = Runtime.getRuntime();
Process p = rc.exec(cmd);
InputStream is = p.getInputStream();
byte[] buff=new byte[128];
StringBuffer sb = new StringBuffer();
while(is.read(buff)!=-1){
sb.append(new String(buff));
}
is.close();
log(sb.toString());
int i=0;
//检查命令执行结果,应该增加一个参数,比如30秒后,还未开启则进行问题升级
log("waitting...");
while(isClosed(port)){
Thread.sleep(1000);
}
log("started...");
return 0;
}
private void log(String msg){
System.err.println(msg);
}
}