背景

这几天遇到个奇怪的问题,因为各种原因吧,需要写一个springboot的程序,对外提供一个接口,然后根据接口的参数执行固定的cmd,其中有个cmd要运行2个小时,奇怪的是在运行几分钟后就hang住了不在执行了,除非kill掉springboot程序才可以

解决办法

单独启动2个线程读取标准错误率和标准输出流,我这里不单独启动线程是不行的

Process proc = Runtime.getRuntime().exec(cmd);
     StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");           
                 StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
                 errorGobbler.start();
                 outputGobbler.start();

     proc.waitFor();

class StreamGobbler extends Thread {
 InputStream is;

 String type;

 StreamGobbler(InputStream is, String type) {
  this.is = is;
  this.type = type;
 }

 public void run() {
  try {
   InputStreamReader isr = new InputStreamReader(is);
   BufferedReader br = new BufferedReader(isr);
   String line = null;
   while ((line = br.readLine()) != null) {
    if (type.equals("Error"))
     LogManager.logError(line);
    else
     LogManager.logDebug(line);
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }
}

异步

因为cmd要执行很久,需要异步返回
SpringbootAlication处加上@EnableAsync,在对应的接口处加上 @Async即可

@SpringBootApplication
@EnableAsync
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}
  @GetMapping("/devops")
  @Async
   public String devops(String id){
        return "ok:"+id;
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注