我有一个 Spring Boot 应用程序,它创建一个线程,在调用 SpringApplication.exit() 之前监视空闲时间,以终止长时间空闲的应用程序..并且我有一个服务 Web 请求的 Restcontroller 类..
问题是,即使在调用 SpringApplication.exit() 之后, Controller 似乎也会在应用程序本身退出之前的一小段时间内接受传入连接。当 Controller 接受新的传入连接,然后之前对 SpringApplication.exit() 的调用生效并导致应用程序退出时,这会导致客户端突然终止。
//伪代码
@RestController
public class AppController {
@PostMapping("/testproc")
public ExitStatus process(@RequestBody Job testJob) {
logger.info("Job batch Id passed: {}", testJob.batchId);
//do processing
if(shutdownFlag) {
//report error to client
} else {
//do regular processing
}
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
ctx = SpringApplication.run(MyApplication.class, args);
Thread shutdownThread = new Thread(new Runnable() {
//check for some condition
if(shutdownFlag) {
logger.info("Exiting");
SpringApplication.exit(ctx, () -> 0);
return;
}
});
shutdownThread.start();
}
}
生成的日志:
2019-03-23 02:02:46.439 INFO 13484 --- [ Thread-10] c.i.e.newgenv1.svc.MyApplication : Exiting 2019-03-23 02:02:46.441 INFO 13484 --- [ Thread-10] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6660a289: startup date [Sat Mar 23 02:02:29 IST 2019]; root of context hierarchy 2019-03-23 02:02:46.509 INFO 13484 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2019-03-23 02:02:46.665 INFO 13484 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 156 ms 2019-03-23 02:02:47.559 INFO 13484 --- [nio-8081-exec-2] c.i.etl.newgenv1.svc.AppController : Job batch Id passed: 23 2019-03-23 02:02:53.828 INFO 13484 --- [ Thread-10] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
请注意记录的行。关闭线程生成的“Exiting”行发生在 Controller 建立连接并打印批处理 ID 之前
在这些时间里,我要么需要阻止 Controller 拾取新连接,要么向客户端报告错误代码。但问题是 Controller 建立了连接,但在报告错误之前,应用程序退出了。
我什至尝试了此处概述的优雅关闭逻辑:https://dzone.com/articles/graceful-shutdown-spring-boot-applications
但仍然没有帮助..
最佳答案
您可以添加一个拦截器来检查是否启动了关闭。如果没有,流程将继续正常执行,否则应丢弃请求并发送正确的响应。
关于java - Spring Boot应用程序关闭时不会禁止新的传入连接,但会突然退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308016/