下面是示例代碼,即
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
log.info("Starting...");
mainThread.start();
mainThread.join();
log.info("Exiting...");
}
@EventListener
public void onApplicationEvent(ContextClosedEvent event) {
log.info("Inside on ApplicationEvent");
mainThread.interrupt();
log.info("Thread Interupted");
}
@Override
public void run() {
try {
someAppLogic.doLogic();
} catch (Exception e) {
if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) {
log.info("Interrupted...");
} else {
log.error("Exception occurred", e);
exitCode = 1;
}
}
}
- someAppLogic.doLogic(); 在 Spring Boot 應用程式啟動時在 mainThread 中呼叫
- 目標是在 someAppLogic.doLogic(); 中出現例外時在 ApplicationEvent 的方法中設定 mainThread 中斷;并有一個退出代碼為 1。
但問題是onApplicationEvent 內部的 main.interrupt() 永遠不會在 run 方法出現例外的情況下被呼叫,即當 someAppLogic.doLogic() 拋出例外時。
這個 Spring boot 應用程式將部署在 Kubernetes 中,因此包含它的 pod 應該正常關閉。
所以問題是如何處理 someAppLogic.doLogic(); 拋出的任何例外;優雅地發送退出代碼為 1 ?
uj5u.com熱心網友回復:
您需要在 ConfigurableApplicationContext 上呼叫 close() 才能發布 ContextClosedEvent。
//you need to figure out how to get hold of this object
private ConfigurableApplicationContext context;
@Override
public void run() {
try {
someAppLogic.doLogic();
} catch (Exception e) {
if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) {
log.info("Interrupted...");
} else {
log.error("Exception occurred", e);
exitCode = 1;
//call close
context.close();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/438153.html
