背景:生产上的服务有时会被注册中心(eureka)踢掉,故而需要重启服务器上的某个服务。
@Slf4j
@Service
public class CellShellBusiness {
public int runRestartApplication(CellSellArg arg) throws Exception {
File file = new File("/data/work/" + arg.getServerName());
if (!file.exists() && !file.isDirectory()) {
throw new BusinessException(-1, "文件夹不存在!");
}
return this.runCommand(file, "./run.sh");
}
public int runCommand(File workDirector, String... cmd) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
processBuilder.directory(workDirector);
log.info("processBuilder.environment:");
log.info("env:{}", processBuilder.environment());
log.info("工作目录 pwd:{}", processBuilder.directory());
Process shellProcess = processBuilder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(shellProcess.getInputStream(), StandardCharsets.UTF_8));
BufferedReader stdError = new BufferedReader(new InputStreamReader(shellProcess.getErrorStream(), StandardCharsets.UTF_8));
//返回值,0为正确执行
int runningStatus = 0;
try {
//等待命令执行
// taskExecutor.execute(());
runningStatus = shellProcess.waitFor();
} catch (InterruptedException e) {
log.error("命令执行失败, error:" + e);
} finally {
log.info("running status:{}", runningStatus);
}
/*显示日志*/
String resultString;
while (null != (resultString = stdError.readLine())) {
//问题,fabric的info输出,这里需要getErrorStream获取到
log.info("stdError {}", resultString);
}
while (null != (resultString = stdInput.readLine())) {
log.info("stdInput {}", resultString);
}
// 销毁进程
if (shellProcess.isAlive()) {
shellProcess.destroy();
}
this.closeStream(stdInput);
this.closeStream(stdError);
return runningStatus;
}
private void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
log.error("关闭连接失败,error : " + e);
}
}
}
}
@Data
public class CellSellArg {
private String serverName;
}