LoginSignup
21
20

More than 5 years have passed since last update.

Spring Boot で @Async の処理が待ってから落ちるようにする

Last updated at Posted at 2016-04-06

Spring Boot で @Async をつけた処理は非同期で実行されますが、
そのままだとアプリ停止時に容赦なく途中で落ちます。
悲劇……それを回避したい。

以下の手順で実現できます。

  1. @Asyncで使われるプールを指定
  2. アプリ停止時に、プール内のタスクが完了するまで待つようにする

プールの定義

@Bean
public ThreadPoolTaskExecutor asyncExecutor() {
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();

    // 最大3タスク
    threadPool.setCorePoolSize(3);
    threadPool.setMaxPoolSize(3);

    // アプリ終了時にshutdown
    threadPool.setWaitForTasksToCompleteOnShutdown(true);
    // shutdown時に実行完了を最大15分待つ
    threadPool.setAwaitTerminationSeconds(60 * 15);

    return threadPool;
}

setAwaitTerminationSecondsも設定しないと、結局待たないので注意

@Asyncの設定でプールを指定

@Configuration
@EnableAsync
class AsyncConfigurer extends AsyncConfigurerSupport {

    @Autowired
    private ThreadPoolTaskExecutor asyncExecutor;

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor;
    }
}

@Asyncで実行するプールを指定する事もできる。これはデフォルトで使われる物を指定。

ThreadPoolTaskExecutorgetAsyncExecutor で作ればよくね?とも思ったけど、停止時のあれこれが動かなくなる。Beanである事が大事。

これで動かした感じ、kill -15しても終わってから落ちる。イェイ!

21
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
20