1

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;
}
 }
Jessie
  • 963
  • 5
  • 16
  • 26

1 Answers1

1

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

Max Farsikov
  • 2,451
  • 19
  • 25
  • Thank you for your reply..... Was able to invoke shutdown hook... But unable to print the log in predestroy method in grateful shutdown.... may be logger console is closed before...Can u suggest on this – Jessie Aug 13 '18 at 21:34