我使用Spring Boot进行此配置:
@Bean
public TaskExecutor a() {
return new SimpleAsyncTaskExecutor();
}
@Bean
public CommandLineRunner b() {
return (String... args) -> {
RunnableTask task = SomeRunnableTask();
a().execute(task);
};
}
当该线程停止时(出于任何原因)我想关闭Spring Boot应用程序。
该线程是一个长时间运行的进程,连接到数据库,webservice,socket ......所以很可能在某些时候它会失败。
线程停止时关闭Spring Boot的正确方法是什么?我不应该使用Spring的SimpleAsyncTaskExecutor
吗?
谢谢!
答案 0 :(得分:1)
Spring Boot有一个ShutdownEndpoint
允许正常关闭应用程序(默认情况下不启用)。
你必须看看它:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500L); // For the response to be sent back to the requester
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
ShutdownEndpoint.this.context.close(); // The ConfigurableApplicationContext
}
});
thread.setContextClassLoader(getClass().getClassLoader());
thread.start();