Не использовать SimpleAsyncTaskExecutor
- SimpleAsyncTaskExecutor создает новый поток для каждого запроса, вместо этого используйте ThreadPoolTaskExecutor
и настраивайте два свойства, указанных ниже.
/**
* Set whether to wait for scheduled tasks to complete on shutdown,
* not interrupting running tasks and executing all tasks in the queue.
* <p>Default is "false", shutting down immediately through interrupting
* ongoing tasks and clearing the queue. Switch this flag to "true" if you
* prefer fully completed tasks at the expense of a longer shutdown phase.
* <p>Note that Spring's container shutdown continues while ongoing tasks
* are being completed. If you want this executor to block and wait for the
* termination of tasks before the rest of the container continues to shut
* down - e.g. in order to keep up other resources that your tasks may need -,
* set the {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"}
* property instead of or in addition to this property.
* @see java.util.concurrent.ExecutorService#shutdown()
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
this.waitForTasksToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
}
/**
* Set the maximum number of seconds that this executor is supposed to block
* on shutdown in order to wait for remaining tasks to complete their execution
* before the rest of the container continues to shut down. This is particularly
* useful if your remaining tasks are likely to need access to other resources
* that are also managed by the container.
* <p>By default, this executor won't wait for the termination of tasks at all.
* It will either shut down immediately, interrupting ongoing tasks and clearing
* the remaining task queue - or, if the
* {@link #setWaitForTasksToCompleteOnShutdown "waitForTasksToCompleteOnShutdown"}
* flag has been set to {@code true}, it will continue to fully execute all
* ongoing tasks as well as all remaining tasks in the queue, in parallel to
* the rest of the container shutting down.
* <p>In either case, if you specify an await-termination period using this property,
* this executor will wait for the given time (max) for the termination of tasks.
* As a rule of thumb, specify a significantly higher timeout here if you set
* "waitForTasksToCompleteOnShutdown" to {@code true} at the same time,
* since all remaining tasks in the queue will still get executed - in contrast
* to the default shutdown behavior where it's just about waiting for currently
* executing tasks that aren't reacting to thread interruption.
* @see java.util.concurrent.ExecutorService#shutdown()
* @see java.util.concurrent.ExecutorService#awaitTermination
*/
public void setAwaitTerminationSeconds(int awaitTerminationSeconds) {
this.awaitTerminationSeconds = awaitTerminationSeconds;
}
Relavant part
Установите максимальное количество секунд, которое этот исполнитель должен блокировать при завершении работы, чтобы дождаться завершения выполнения оставшихся задач, прежде чем остальная часть контейнера продолжит работу. Это особенно полезно, если вашим оставшимся задачам, вероятно, потребуется доступ к другим ресурсам, которые также управляются контейнером.
Вы можете настроить использование автоматической конфигурации Spring для управления свойствами выполнения задачи ( предпочтительнее ) или программно с @Bean
аннотацией
Spring boot в 2.1.0 обеспечивает автоматическую настройку для исполнителей задач и использует поддержку @EnableAsync
и Spring MVC Asyn c.
Для приложения не требуется настройка bean-компонента executor / webMvcConfigurer из приложения. Поэтому удалите тот, который у вас есть, и он должен быть хорошим.
Вы можете настроить его, используя файл applicationaion properties / yml с spring.task.execution.*
.
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=60
Полный список можно найти here
Подробнее here
и here
ИЛИ
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(5);
taskExecutor.waitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
return taskExecutor;
}