@EnableAsync

코딩냥이·2024년 9월 10일

Annotation

목록 보기
34/34

@EnableAsync

@EnableAsync 어노테이션은 스프링 프레임워크에서 비동기 메서드 실행을 활성화하는 데 사용되는 어노테이션입니다.

기능

  1. 스프링 애플리케이션에서 비동기 처리 기능을 활성화합니다.
  2. @Async 어노테이션이 붙은 메서드들이 비동기적으로 실행될 수 있도록 합니다.
  3. 기본적으로 SimpleAsyncTaskExecutor를 사용하여 비동기 작업을 처리합니다.

사용 방법

기본적인 사용 방법은 다음과 같습니다:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfig {
    // 추가적인 비동기 설정이 필요한 경우 여기에 작성
}

주요 특징

  1. 설정 클래스에 적용: 주로 @Configuration 어노테이션과 함께 사용됩니다.
  2. 비동기 실행 활성화: @Async 어노테이션이 붙은 메서드들을 비동기적으로 실행할 수 있게 합니다.
  3. Executor 커스터마이징: 기본 Executor를 커스터마이즈하여 비동기 작업의 실행 방식을 제어할 수 있습니다.
  4. 프록시 기반: 스프링의 AOP 프록시 메커니즘을 사용하여 비동기 실행을 구현합니다.

고급 사용법

1. 커스텀 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();
    }
}

2. 특정 빈에 대한 비동기 처리 제한

@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() {
        // 비동기 작업 수행
    }
}

3. 조건부 비동기 활성화

특정 조건에 따라 비동기 처리를 활성화할 수 있습니다:

@Configuration
@ConditionalOnProperty(name = "async.enabled", havingValue = "true", matchIfMissing = true)
@EnableAsync
public class AsyncConfig {
    // 설정 내용
}

주의사항

  1. 자가 호출 문제: 같은 클래스 내에서 @Async 메서드를 호출하면 비동기로 동작하지 않습니다.
  2. 예외 처리: 비동기 메서드에서 발생한 예외는 호출자에게 전파되지 않으므로 별도의 예외 처리가 필요합니다.
  3. 트랜잭션: 비동기 메서드는 호출자의 트랜잭션 컨텍스트를 공유하지 않습니다.
  4. 테스트: 비동기 메서드의 테스트는 일반 동기 메서드와 다른 접근이 필요합니다.

베스트 프랙티스

  1. 적절한 스레드 풀 설정: 애플리케이션의 요구사항에 맞는 적절한 스레드 풀 크기를 설정하세요.
  2. 예외 처리: AsyncUncaughtExceptionHandler를 구현하여 비동기 메서드의 예외를 적절히 처리하세요.
  3. 모니터링: 비동기 작업의 실행 상태와 성능을 모니터링하세요.
  4. 테스트: 비동기 동작을 고려한 테스트 케이스를 작성하세요.
  5. 문서화: 비동기 메서드의 동작과 제약사항을 명확히 문서화하세요.

테스트

@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

profile
HelloMeow~!

0개의 댓글