@Async 어노테이션은 스프링 프레임워크에서 메소드를 비동기적으로 실행할 수 있게 해주는 어노테이션입니다.
기본적인 사용 방법은 다음과 같습니다:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Async
public void sendEmail(String to, String subject, String content) {
// 이메일 전송 로직 (시간이 걸리는 작업)
System.out.println("Sending email to " + to);
// ... 이메일 전송 코드 ...
}
}
Future 또는 CompletableFuture를 사용하여 비동기 작업의 결과를 처리할 수 있습니다.@Async를 사용하려면 다음과 같이 설정해야 합니다:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig {
// 추가 설정이 필요한 경우 여기에 작성
}
@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;
}
}
@Async
public Future<String> asyncMethodWithReturnType() {
// 시간이 걸리는 작업 수행
return new AsyncResult<>("작업 완료");
}
@Async
public CompletableFuture<String> asyncMethodWithCompletableFuture() {
// 시간이 걸리는 작업 수행
return CompletableFuture.completedFuture("작업 완료");
}
@Async
public void asyncMethodWithExceptionHandler() {
try {
// 비동기 작업 수행
} catch (Exception e) {
// 예외 처리 로직
}
}
@Async 메소드를 호출하면 비동기로 동작하지 않습니다.@Async는 public 메소드에만 적용됩니다.@Async 메소드를 테스트할 때:
@SpringBootTest
class EmailServiceTest {
@Autowired
private EmailService emailService;
@Test
void testAsyncMethod() throws InterruptedException {
emailService.sendEmail("test@example.com", "Test", "Content");
// 비동기 작업이 완료될 때까지 대기
Thread.sleep(1000);
// 여기서 작업 결과를 확인하거나 모의 객체를 통해 호출 여부를 검증
}
}
@Async 어노테이션은 스프링 애플리케이션에서 비동기 처리를 간단하게 구현할 수 있게 해주는 강력한 도구입니다. 이를 통해 장시간 실행되는 작업이나 외부 서비스 호출 등을 효율적으로 처리할 수 있으며, 애플리케이션의 응답성과 확장성을 향상시킬 수 있습니다. 그러나 비동기 프로그래밍의 복잡성, 리소스 관리, 예외 처리 등의 측면을 신중히 고려해야 합니다. 적절히 사용하면 애플리케이션의 성능을 크게 개선할 수 있지만, 무분별한 사용은 오히려 시스템의 복잡성을 증가시키고 디버깅을 어렵게 만들 수 있습니다.
@EnableAsync
@Scheduled
@Configuration
@Service
@SpringBootTest