@EnableAsync 어노테이션은 스프링 프레임워크에서 비동기 메서드 실행을 활성화하는 데 사용되는 어노테이션입니다.
@Async 어노테이션이 붙은 메서드들이 비동기적으로 실행될 수 있도록 합니다.SimpleAsyncTaskExecutor를 사용하여 비동기 작업을 처리합니다.기본적인 사용 방법은 다음과 같습니다:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig {
// 추가적인 비동기 설정이 필요한 경우 여기에 작성
}
@Configuration 어노테이션과 함께 사용됩니다.@Async 어노테이션이 붙은 메서드들을 비동기적으로 실행할 수 있게 합니다.Executor를 커스터마이즈하여 비동기 작업의 실행 방식을 제어할 수 있습니다.@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.setThreadNamePrefix("MyAsync-");
executor.initialize();
return executor;
}
}
@Service
public class AsyncService {
@Async("threadPoolTaskExecutor")
public void asyncMethod() {
// 비동기 작업 수행
}
}
특정 조건에 따라 비동기 처리를 활성화할 수 있습니다:
@Configuration
@ConditionalOnProperty(name = "async.enabled", havingValue = "true", matchIfMissing = true)
@EnableAsync
public class AsyncConfig {
// 설정 내용
}
@Async 메서드를 호출하면 비동기로 동작하지 않습니다.AsyncUncaughtExceptionHandler를 구현하여 비동기 메서드의 예외를 적절히 처리하세요.@EnableAsync가 적용된 설정을 테스트할 때:
@SpringBootTest
@TestPropertySource(properties = "async.enabled=true")
class AsyncConfigTest {
@Autowired
private AsyncService asyncService;
@Test
void testAsyncMethod() throws InterruptedException {
asyncService.asyncMethod();
// 비동기 작업의 완료를 기다리는 로직
// 예: Thread.sleep() 또는 CountDownLatch 사용
// 결과 확인 로직
}
}
@EnableAsync 어노테이션은 스프링 애플리케이션에서 비동기 처리를 쉽게 구현할 수 있게 해주는 강력한 도구입니다. 이를 통해 장시간 실행되는 작업, I/O 바운드 작업, 외부 서비스 호출 등을 효율적으로 처리할 수 있으며, 애플리케이션의 응답성과 확장성을 향상시킬 수 있습니다. 그러나 비동기 프로그래밍의 복잡성, 예외 처리, 리소스 관리 등의 측면을 신중히 고려해야 합니다. 적절히 사용하면 애플리케이션의 성능을 크게 개선할 수 있지만, 무분별한 사용은 시스템의 복잡성을 증가시키고 디버깅을 어렵게 만들 수 있습니다.
@Async
@Configuration
@EnableScheduling
@Conditional
@SpringBootTest