@SpringBootApplication 어노테이션이 정의된 클래스에 @EnableAsync 어노테이션을 추가한다.
비동기 테스트용 @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);
}
}
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
※ 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;
}
@Async("asyncThreadPoolTaskExecutor")
public void asyncHello(int i) {
log.info("async i = " + i);
}
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