[BAEL-3288] - Graceful Shutdown of a Spring Boot Application

This commit is contained in:
macroscopic64 2019-09-22 19:15:26 +05:30
parent 925b93b91c
commit c1a6515fcf
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package com.baeldung.gracefulshutdown;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.baeldung.gracefulshutdown"})
public class GracefulShutdownApplication {
public static void main(String args[]) {
SpringApplication.run(GracefulShutdownApplication.class, args);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.gracefulshutdown.beans;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
@Component
public class LongRunningProcessBean {
private static final Logger LOG = LoggerFactory.getLogger(LongRunningProcessBean.class);
@Autowired
private TaskExecutor taskExecutor;
@PostConstruct
public void runTaskOnStartup() {
LOG.info("runTaskOnStartup entering");
for (int i = 0; i < 3; i++) {
final int processNumber = i;
taskExecutor.execute(() -> {
try {
LOG.info("Long running process {} using threadpool started", processNumber);
Thread.sleep(60_000);
LOG.info("Long running process {} using threadpool completed", processNumber);
} catch (Exception e) {
LOG.error("Error while executing task", e);
}
});
}
LOG.info("runTaskOnStartup exiting");
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.gracefulshutdown.config;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableScheduling
public class SpringConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(SpringConfiguration.class);
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(2);
taskExecutor.setMaxPoolSize(2);
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(30);
taskExecutor.initialize();
return taskExecutor;
}
@PreDestroy
public void destroy() {
LOG.info("Shutdown initiated");
}
}