下面是示例代码,即
@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;
}
}
}但是问题是,在运行方法出现异常时,main.interrupt()在onApplicationEvent中永远不会获得调用,也就是说,当someAppLogic.doLogic()抛出异常时。
这个Spring引导应用程序将部署在Kubernetes中,因此包含此功能的pod应该会优雅地关闭。
因此,问题是如何处理由someAppLogic.doLogic()引发的任何异常;优雅地将exitcode发送为1?
发布于 2022-03-04 17:24:17
您需要调用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://stackoverflow.com/questions/71353986
复制相似问题