我已經撰寫了一個用于檔案上傳的 Spring Boot 應用程式。我希望我的 spring boot 應用程式在執行完成后關閉正在運行的 localhost 8080 。
spring boot執行完成后有沒有辦法殺死服務器
有人可以幫我嗎
想以編程方式殺死本地主機。
uj5u.com熱心網友回復:
您可以通過創建 bean 以下列方式執行此操作:
@Component
class ShutdownManager {
@Autowired
private ApplicationContext appContext;
public void initiateShutdown(int returnCode){
SpringApplication.exit(appContext, () -> returnCode);
}
}
你可以在任何地方自動裝配這個 bean 并使用initialShutdown 函式來關閉應用程式背景關系和服務器,如下所示:
@Component
public class Controller{
@Autowired
private final ShutdownManager shutdownManager;
@GetMapping("/")
public void Shutdown(){
shutdownManager.initiateShutdown(0);
}
}
或者您可以簡單地在任何控制器上自動裝配此 bean,并在您想要的任何位置使用回傳碼呼叫此方法。
uj5u.com熱心網友回復:
方法一:
如果您正在使用執行器模塊,則可以通過 JMX 或 HTTP 關閉應用程式(如果啟用了端點)。
添加到 application.properties:
endpoints.shutdown.enabled=true
根據端點的暴露方式,敏感引數可以用作安全提示。
例如,敏感端點在通過 HTTP 訪問時將需要用戶名/密碼(如果未啟用 Web 安全性,則直接禁用)。
你可以檢查一下:spring boot documentation
方法 2: 這是另一個選項,不需要您更改代碼或公開關閉的端點。創建以下腳本并使用它們來啟動和停止您的應用程式。
啟動.sh
#!/bin/bash
kill $(cat ./pid.file)
使用保存的行程 ID 停止您的應用
start_silent.sh
#!/bin/bash
nohup ./start.sh > foo.out 2> foo.err < /dev/null &
如果您需要從遠程機器或 CI 管道使用 ssh 啟動應用程式,則使用此腳本來啟動您的應用程式。直接使用 start.sh 可以讓 shell 掛起。
例如之后。重新/部署您的應用程式,您可以使用以下命令重新啟動它:
sshpass -p password ssh -oStrictHostKeyChecking=no userName@www.domain.com 'cd /home/user/pathToApp; ./stop.sh; ./start_silent.sh'
方法 3 這里是一個 Maven 快速示例,供 Maven 用戶配置 HTTP 端點以使用 spring-boot-starter-actuator 關閉 Spring Boot Web 應用程式,以便您可以復制和粘貼: 1.Maven pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.application.properties:
#No auth protected
endpoints.shutdown.sensitive=false
#Enable shutdown endpoint
endpoints.shutdown.enabled=true
此處列出了所有端點
3.發送關閉應用的post方法: curl -X POST localhost:port/shutdown
安全提示:
如果您需要關閉方法 auth protected,您可能還需要
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置資訊
uj5u.com熱心網友回復:
只需將此代碼放在上傳代碼的末尾:
@Controller
public class Upload {
@Autowired
private ApplicationContext context;
@PostMapping("/upload")
public void uploadFile(){
// do upload the file here.
//after uploading shutdown the spring boot application.
SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
}
}
我自己檢查過它正在作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512468.html
