4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SpringBootでキューを使いたかった

Posted at

SpringBootでキューに処理を積む流れ

  1. pomにlombokを追加
  2. mainメソッドを持つクラスにスレッドプールのBeanを作成+@EnableAsyncをつける
  3. 非同期処理を作成する。対象メソッドに@Async("スレッド名")をつける
  4. 呼び出しは一般的なメソッドと違いはない

pom

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
    <scope>provided</scope>
  </dependency>

Applicationクラス

@SpringBootApplication
@EnableAsync
public class Application {

    省略

    /**
     *
     * @return キューを使用するためのスレッドプール
     */
    @Bean("Thread1")
    public Executor taskExecutor() {

        final Logger log = LoggerFactory.getLogger(Quuhelper.class);

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //スレッドを並列でいくつ立てるか
        executor.setCorePoolSize(1);
        //キューがマックスになったときにスレッドの数をいくつまで増やすか
        executor.setMaxPoolSize(2);
        //キューはいくつまで積むか
        executor.setQueueCapacity(500);
        executor.initialize();
        return executor;
    }
}

処理部分

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;



@Slf4j
@Service
public class Quuhelper {

    static final Logger log = LoggerFactory.getLogger(Quuhelper.class);

    /**
     * テスト
     */
    @Async("Thread1")
    public void heavyTask() {
        try {
            log.info("start task");
            TimeUnit.SECONDS.sleep(10);
            log.info("end task");
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

非同期処理呼び出し元(ControllerやService)

    @Autowired
    private Quuhelper quuhelper;

    @GetMapping(path = "/test")
    public void test() {
        quuhelper.heavyTask();
    }

参考
Spring 非同期タスクの同時実行数を制限する

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?