@RestController 비동기@Async 호출 #1

catch me if u can!·2021년 6월 23일
0
  1. @SpringBootApplication 어노테이션이 정의된 클래스에 @EnableAsync 어노테이션을 추가한다.

  2. 비동기 테스트용 @RestController와 @Service를 아래와 같이 생성한다.

@RestController
public class TestController {
  @Autowired
  private TestAsyncService testAsyncService;
  
  @GetMapping("/test/asyncCall")
  public void asyncCall() {
    for(int i = 0; i < 10000; i++) {
      asyncService.asyncHello(i);
    }
  }
}

@Log
@Service
public class TestAsyncService {
  @Async
  public void asyncHello(int i) {
    log.info("async i = " + i);
  }
}
  1. http://localhost:8080/test/asyncCall 을 호출하여 호출되는 스레드번호를 확인하여 정상적으로 비동기 호출이 되는지 확인한다. 아래와 같이 task-20, task17, task-22 서로다른 스레드에서 asyncHello 작업이 처리되는 것을 확인할 수 있다.
20210623 11:26:10.445 [task-20] INFO c.g.t.s.TestAsyncService - async i = 5748 
20210623 11:26:10.446 [task-17] INFO c.g.t.s.TestAsyncService - async i = 5777 
20210623 11:26:10.446 [task-20] INFO c.g.t.s.TestAsyncService - async i = 5778 
20210623 11:26:10.446 [task-20] INFO c.g.t.s.TestAsyncService - async i = 5782 
20210623 11:26:10.445 [task-22] INFO c.g.t.s.TestAsyncService - async i = 5755 
  1. @Async는 기본값으로 SimpleAsyncTaskExecutor를 사용하기 때문에 실행 시 마다 필요한 수만큼 스레드를 생성하고 실행하는 방식이라 성능이 떨어지므로, 스레드풀을 이용하는 방식으로 변경한다.
    @SpringBootApplication 어노테이션이 정의된 클래스에 아래 @Bean정의를 추가한다.
    (ThreadPoolTaskExecutor를 사용하여 기본 4개 최대 8개의 스레드를 생성하여 실행)

※ setQueueCapacity는 Max스레드가 작동 시, 대기큐의 수를 설정하는 값(기본값: Integer.MAX_VALUE)이며, 설정 값을 초과하여 요청이 발생하면 예외가 발생한다.

@Bean(name="asyncThreadPoolTaskExecutor")
public Executor  asyncThreadPoolTaskExecutor() {
  ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
  taskExecutor.setCorePoolSize(4);
  taskExecutor.setMaxPoolSize(8);
  //taskExecutor.setQueueCapacity(10000);
  taskExecutor.setThreadNamePrefix("Executor-");
  taskExecutor.initialize();		
  return taskExecutor;
}
  1. @Async 어노테이션에 asyncThreadPoolTaskExecutor를 설정한다.
@Async("asyncThreadPoolTaskExecutor")
public void asyncHello(int i) {
  log.info("async i = " + i);
}
  1. setThreadNamePrefix에서 설정한 "Executor-"가 스레드명에 적용되어 출력된다.
20210623 13:41:03.759 [Executor-2] INFO c.g.t.s.TestAsyncService - async i = 9902 
20210623 13:41:03.759 [Executor-4] INFO c.g.t.s.TestAsyncService - async i = 9903 
20210623 13:41:03.759 [Executor-3] INFO c.g.t.s.TestAsyncService - async i = 9904 
20210623 13:41:03.759 [Executor-5] INFO c.g.t.s.TestAsyncService - async i = 9905 
20210623 13:41:03.759 [Executor-4] INFO c.g.t.s.TestAsyncService - async i = 9907 

Spring @Async 비동기처리
Spring Boot @Async 어떻게 동작하는가?

profile
마쿠투소케 난쿠로나이사

0개의 댓글