兩個(gè)東西:
1. 一個(gè)controller方法那槽,用于接收前端的請(qǐng)求,并調(diào)用linux的shell文件
2.shell文件
shell文件:server.sh
#!/bin/bash
app='eaglenos-admin.jar'
cmd=$1
pid=`ps -ef|grep java|grep $app|awk '{print $2}'`
startup(){
nohup /opt/java/jdk1.8.0_311/bin/java -jar -Dlogging.config="./logback.xml" -Dserver.port=28080 eaglenos-admin.jar --spring.config.location=file:./application.yml,file:./application-druid.yml>/dev/null 2>log &
}
if [ ! $cmd ]; then
echo "Please specify args 'start|restart|stop'"
exit
fi
if [ $cmd == 'start' ]; then
if [ ! $pid ]; then
startup
else
echo "$app is running! pid=$pid"
fi
fi
if [ $cmd == 'restart' ]; then
if [ $pid ]
then
echo "$pid will be killed after 3 seconds!"
sleep 3
kill -9 $pid
fi
startup
fi
if [ $cmd == 'stop' ]; then
if [ $pid ]; then
echo "$pid will be killed after 3 seconds!"
sleep 3
kill -9 $pid
fi
echo "$app is stopped"
fi
controller工具類:SysUtils.java
@RestController
public class SysUtils extends BaseController {
//腳本的地址
@Value("${refresh.scriptPath}")
private String scriptPath;
/**
* 觸發(fā)升級(jí)
* @return
* @throws Exception
*/
@RequestMapping("/refresh")
private AjaxResult run() throws Exception {
ProcessBuilder sh = new ProcessBuilder("sh",scriptPath,"restart");
asynExeLocalComand(null, sh);
return AjaxResult.success();
}
/**
* 用來檢查服務(wù)是否正常
* @return
* @throws IOException
*/
@RequestMapping("/getParam")
private String getParam() throws IOException {
return scriptPath;
}
public static void asynExeLocalComand(File file, ProcessBuilder pb) throws IOException {
// 不使用Runtime.getRuntime().exec(command)的方式,因?yàn)闊o法設(shè)置以下特性
// Java執(zhí)行本地命令是啟用一個(gè)子進(jìn)程處理,默認(rèn)情況下子進(jìn)程與父進(jìn)程I/O通過管道相連(默認(rèn)ProcessBuilder.Redirect.PIPE)
// 當(dāng)服務(wù)執(zhí)行自身重啟的命令時(shí),父進(jìn)程關(guān)閉導(dǎo)致管道連接中斷,將導(dǎo)致子進(jìn)程也崩潰,從而無法完成后續(xù)的啟動(dòng)
// 解決方式,(1)設(shè)置子進(jìn)程IO輸出重定向到指定文件;(2)設(shè)置屬性子進(jìn)程的I/O源或目標(biāo)將與當(dāng)前進(jìn)程的相同,兩者相互獨(dú)立
if (file == null || !file.exists()) {
// 設(shè)置屬性子進(jìn)程的I/O源或目標(biāo)將與當(dāng)前進(jìn)程的相同,兩者相互獨(dú)立
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
} else {
// 設(shè)置子進(jìn)程IO輸出重定向到指定文件
// 錯(cuò)誤輸出與標(biāo)準(zhǔn)輸出,輸出到一塊
pb.redirectErrorStream(true);
// 設(shè)置輸出日志
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(file));
}
// 執(zhí)行命令進(jìn)程
System.out.println(pb.command());
pb.start();
}
}