Spring Boot-调用Shutdownhook的问题

时间:2018-08-12 08:29:49

标签: spring spring-boot spring-boot-actuator shutdown-hook

当我尝试使用ctrl + c或使用以下脚本使用进程ID关闭spring boot应用程序时。不调用Shutdown hook。需要一些解决方案来在Windows和Linux中调用shutdown钩子。

关机脚本:

 SET /P PID_FROM_FILE= < application.pid
 taskkill /pid %PID_FROM_FILE% /f

Gracefulshutdown挂钩类:

@Component
public class GracefulShutdownHook {

private static final Logger LOGGER = LogManager.getLogger   (GracefulShutdownHook.class);

@Autowired
@Qualifier("inboundChannel")
MessageChannel inboundChannel;

@Autowired
@Qualifier("pollingExecutor")
ThreadPoolTaskExecutor pollingExecutor;

  @PreDestroy 
  public void onDestroy() throws Exception {
// First stop the file integration adapter to process files
  inboundChannel.send(new  GenericMessage<String> "@'filesInChannel.adapter'.stop()"));
//  wait till current processing of files is over
 pollingExecutor.shutdown();
 LOGGER.log(Level.INFO, "Application shutdown succesfully");
}
@Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 0;
}
 }

1 个答案:

答案 0 :(得分:1)

您无法在Spring应用程序中处理ctrl-ctaskkill

可以适当地关闭应用程序的一种方法是创建端点POST /shutdown并在其中调用applicationContext.close()

@RestController
public class Shutdowner {

    @Autowired 
    ApplicationContext ctx;

    @PostMapping("/shutdown")
    public void shutdown(){
        ctx.close();
    }
}

可以在此处找到更多示例:https://www.baeldung.com/spring-boot-shutdown