Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot programmatically restart app

I'm developing a Spring Boot app, in which I need to write Java code to shut down the app itself (including its threads), and then restart it. I've tried the following two methods, the first one is to issue a Linux command in Java like the following:

Process p = Runtime.getRuntime().exec("kill -SIGINT " + pid);

where pid is that of the app itself. This has the same effect as pressing "ctrl + c". But having shut down the app successfully this way, I don't know how I can restart it. I tried to issue another command (like "mvn spring-boot:run", which is how I start the app) using the same method but since the app is shut down already, this doesn't work.

Secondly, I've also tried calling the refresh() method of AbstractApplicationContext as follows:

AbstractApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.registerShutdownHook();
appContext.refresh();

But I don't think this kind of context refreshing is the same as restarting?

So what is the proper way to restart a Spring Boot app with Java code? Any help is appreciated, thanks!

like image 675
fittaoee Avatar asked Apr 24 '26 12:04

fittaoee


2 Answers

The gstackoverflow's answer didn't work for me, my solution:

Add dependencies to build.gradle

compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '2.0.0.RELEASE'
compile("org.springframework.boot:spring-boot-starter-actuator")

Autowired RestartEndpoint

@Autowired
private RestartEndpoint restartEndpoint;

Add this to application.properties

management.endpoint.restart.enabled = true

And invoke

    Thread restartThread = new Thread(() -> restartEndpoint.restart());
    restartThread.setDaemon(false);
    restartThread.start();
like image 180
Dicren Avatar answered Apr 27 '26 01:04

Dicren


You need to add spring-boot-starter-actuator and Spring cloud dependencies to your application and use /restart endpoint to restart the app. Here is the documentation:

For a Spring Boot Actuator application there are some additional management endpoints:

  • POST to /env to update the Environment and rebind @ConfigurationProperties and log levels

  • /refresh for re-loading the boot strap context and refreshing the @RefreshScope beans

  • /restart for closing the ApplicationContext and restarting it (disabled by default)

  • /pause and /resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext)

Once done, you can use a REST API call to restart the application (via RestTemplate or curl). This will be cleaner way to restart the app than killing it and re-running it.

like image 21
Darshan Mehta Avatar answered Apr 27 '26 03:04

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!