背景:生产上的服务有时会被注册中心(eureka)踢掉,故而需要重启服务器上的某个服务。

    1. @Slf4j
    2. @Service
    3. public class CellShellBusiness {
    4. public int runRestartApplication(CellSellArg arg) throws Exception {
    5. File file = new File("/data/work/" + arg.getServerName());
    6. if (!file.exists() && !file.isDirectory()) {
    7. throw new BusinessException(-1, "文件夹不存在!");
    8. }
    9. return this.runCommand(file, "./run.sh");
    10. }
    11. public int runCommand(File workDirector, String... cmd) throws IOException {
    12. ProcessBuilder processBuilder = new ProcessBuilder(cmd);
    13. processBuilder.directory(workDirector);
    14. log.info("processBuilder.environment:");
    15. log.info("env:{}", processBuilder.environment());
    16. log.info("工作目录 pwd:{}", processBuilder.directory());
    17. Process shellProcess = processBuilder.start();
    18. BufferedReader stdInput = new BufferedReader(new InputStreamReader(shellProcess.getInputStream(), StandardCharsets.UTF_8));
    19. BufferedReader stdError = new BufferedReader(new InputStreamReader(shellProcess.getErrorStream(), StandardCharsets.UTF_8));
    20. //返回值,0为正确执行
    21. int runningStatus = 0;
    22. try {
    23. //等待命令执行
    24. // taskExecutor.execute(());
    25. runningStatus = shellProcess.waitFor();
    26. } catch (InterruptedException e) {
    27. log.error("命令执行失败, error:" + e);
    28. } finally {
    29. log.info("running status:{}", runningStatus);
    30. }
    31. /*显示日志*/
    32. String resultString;
    33. while (null != (resultString = stdError.readLine())) {
    34. //问题,fabric的info输出,这里需要getErrorStream获取到
    35. log.info("stdError {}", resultString);
    36. }
    37. while (null != (resultString = stdInput.readLine())) {
    38. log.info("stdInput {}", resultString);
    39. }
    40. // 销毁进程
    41. if (shellProcess.isAlive()) {
    42. shellProcess.destroy();
    43. }
    44. this.closeStream(stdInput);
    45. this.closeStream(stdError);
    46. return runningStatus;
    47. }
    48. private void closeStream(Closeable stream) {
    49. if (stream != null) {
    50. try {
    51. stream.close();
    52. } catch (Exception e) {
    53. log.error("关闭连接失败,error : " + e);
    54. }
    55. }
    56. }
    57. }
    58. @Data
    59. public class CellSellArg {
    60. private String serverName;
    61. }