Jessie
Jessie

Reputation: 963

Spring boot - Issue in invoking Shutdownhook

When i try to shutdown the spring boot application using ctrl+c or using process id using below script.. Shutdown hook is not invoked. Require some solution to invoke the shutdown hook both in windows and linux.

Shutdown script:

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

Gracefulshutdown hook class:

@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;
}
 }

Upvotes: 1

Views: 248

Answers (1)

Max Farsikov
Max Farsikov

Reputation: 2763

You can not handle ctrl-c nor taskkill inside your Spring application.

The one of ways you can appropriately shut down your application is to create endpoint POST /shutdown and call applicationContext.close() inside it:

@RestController
public class Shutdowner {

    @Autowired 
    ApplicationContext ctx;

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

More examples can be found here: https://www.baeldung.com/spring-boot-shutdown

Upvotes: 1

Related Questions