@EnableAsync 활성화
@Configuration
@EnableAsync
public class AsyncConfig {
}
TaskExecutor 빈 설정
비동기 작업을 처리할 Thread Pool 을 구성하기 위한 TaskExecutor 빈을 설정
Task : 독립적으로 실행 가능한 작업
비동기 작업 중 발생한 예외 처리를 위한 getAsyncUncaughtExceptionHandler 재정의
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
private int CORE_POOL_SIZE = 10;
private int MAX_POOL_SIZE = 100;
private int QUEUE_CAPACITY = 1000;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(CORE_POOL_SIZE); // 스레드 풀의 기본 크기
executor.setMaxPoolSize(MAX_POOL_SIZE); // 스레드 풀의 최대 크기
executor.setQueueCapacity(QUEUE_CAPACITY); // 대기열 크기
executor.initialize(); // 스레드 풀 초기화
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (exceptionHandler, method, params) ->
log.error("Exception handler for async method '" + method.toGenericString()
+ "' threw unexpected exception itself", exceptionHandler);
}
}
@Async 적용
@Service
public class AsyncService {
@Async
public class asyncMethod() {
// 비동기로 실행될 코드
}
}
호출자에서 비동기 메서드 호출
@Controller
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/doAsync")
public String doAsync() {
// 비동기 메서드 호출
asyncService.asyncMethod();
// ... 다른 작업들
// (호출자는 비동기 메서드가 실행 중일 때 다른 작업 수행 가능)
return "result";
}
}