溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring Boot調(diào)用 Shell 腳本如何實現(xiàn)看門狗功能?

發(fā)布時間:2020-06-23 10:51:56 來源:億速云 閱讀:4698 作者:清晨 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Spring Boot調(diào)用 Shell 腳本如何實現(xiàn)看門狗功能?,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

需要實現(xiàn)看門狗功能,定時檢測另外一個程序是否在運行,使用 crontab 僅可以實現(xiàn)檢測程序是否正在運行,無法做到擴(kuò)展,如:手動重啟、程序升級(如果只需要實現(xiàn)自動升級功能可以使用 inotify)等功能;最后決定使用 Spring Boot 調(diào)用 Shell 腳本來實現(xiàn)

一、腳本

1.1 啟動腳本

#!/bin/bash

ps -ef | grep "demo-app-0.0.1-SNAPSHOT.jar" | grep -v "grep"

if [ "$?" -eq 0 ]
then

# sleep
echo $(date "+%Y-%m-%d %H:%M:%S") "process already started!"

else

nohup java -jar -server /project/watchdog/demo-app-0.0.1-SNAPSHOT.jar &
echo $(date "+%Y-%m-%d %H:%M:%S") "process has been started!"

fi

1.2 重啟腳本

#!/bin/bash

pid=`ps -ef | grep "demo-app-0.0.1-SNAPSHOT.jar" | grep -v "grep" | awk '{print $2}'`

for id in $pid
do
 kill -9 $id
 echo "killed $id"
done

nohup java -jar -server /project/watchdog/demo-app-0.0.1-SNAPSHOT.jar &
echo $(date "+%Y-%m-%d %H:%M:%S") "process has been restarted!"

二、功能實現(xiàn)

將腳本放置在程序的資源目錄下,每次程序啟動時將腳本讀取到指定位置,然后再通過定時任務(wù)執(zhí)行腳本

配置內(nèi)容:

shell:
 directory: /project/watchdog
 startupFileName: startup.sh
 restartFileName: restart.sh
@Configuration
@ConfigurationProperties(prefix = "shell")
public class ShellProperties {

 private String directory;
 private String startupFileName;
 private String restartFileName;

 /* getter & setter */

 public String getFullName(String fileName) {
 return directory + File.separator + fileName;
 }
}

2.1 啟動時將腳本讀取到指定位置

@Component
public class InitRunner implements CommandLineRunner {

 @Autowired
 private ShellProperties shellProperties;

 @Autowired
 ResourceLoader resourceLoader;

 @Override
 public void run(String... args) throws Exception {
 generateFile(shellProperties.getStartupFileName());
 generateFile(shellProperties.getRestartFileName());
 }

 private void generateFile(String fileName) throws IOException {

 String fileFullName = shellProperties.getFullName(fileName);
 File file = new File(fileFullName);
 if(file.exists()) {
 return;
 }

 // 如果文件已存在,F(xiàn)ileWriter 會先刪除再新建
 FileWriter fileWriter = new FileWriter(fileFullName);

 Resource resource = resourceLoader.getResource("classpath:" + fileName);
 InputStream inputStream = resource.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

 String data;
 while ((data = bufferedReader.readLine()) != null) {
 fileWriter.write(data + "\n");
 }

 bufferedReader.close();
 inputStreamReader.close();
 inputStream.close();

 fileWriter.close();

 // 設(shè)置權(quán)限,否則會報 Permission denied
 file.setReadable(true);
 file.setWritable(true);
 file.setExecutable(true);
 }
}

2.2 定時任務(wù)定時任務(wù)執(zhí)行腳本

@Component
public class ShellTask {

 private static final Logger logger = LoggerFactory.getLogger(ShellTask.class);

 @Autowired
 private ShellProperties shellProperties;

 @Scheduled(cron = "0/10 * * * * ? ")
 public void start() throws IOException {
 executeShell(shellProperties.getStartupFileName());
 }

 private void executeShell(String fileName) throws IOException {

 String fileFullName = shellProperties.getFullName(fileName);
 File file = new File(fileFullName);
 if(!file.exists()) {
 logger.error("file {} not existed!", fileFullName);
 return;
 }

 ProcessBuilder processBuilder = new ProcessBuilder(fileFullName);
 processBuilder.directory(new File(shellProperties.getDirectory()));

 Process process = processBuilder.start();

// String input;
// BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
// BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// while ((input = stdInput.readLine()) != null) {
// logger.info(input);
// }
// while ((input = stdError.readLine()) != null) {
// logger.error(input);
// }

 int runningStatus = 0;
 try {
 runningStatus = process.waitFor();
 } catch (InterruptedException e) {
 logger.error("shell", e);
 }

 if(runningStatus != 0) {
 logger.error("failed.");
 }else {
 logger.info("success.");
 }
 }
}

2.3 擴(kuò)展

本例只實現(xiàn)了定時檢測程序是否運行,如果沒有運行則啟動程序;如有需要可以添加接口,調(diào)用接口重啟程序;或者添加定時任務(wù)定時檢測程序是否有更新,如果有更新則下載新的 jar 包然后重啟程序

看門狗程序自己可以使用 crontab 定時檢測是否正在運行,模仿上面的啟動腳本編寫看門狗的啟動腳本,然后添加定時任務(wù):

crontab -e
*/10 * * * * /project/watchdog/watchdog.sh
sudo systemctl reload crond.service

關(guān)于Spring Boot調(diào)用 Shell 腳本如何實現(xiàn)看門狗功能?就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI