본문 바로가기

Study Information Technology

Spring Boot의 비동기 처리와 Async 어노테이션 활용하기

728x90
반응형

Spring Boot의 비동기 처리와 @Async 어노테이션 활용하기

Overview

Spring Boot는 비동기 프로그래밍을 통해 애플리케이션의 응답성을 향상시킬 수 있는 강력한 기능을 제공합니다. 특히, @Async 어노테이션을 활용하면 특정 메서드를 별도의 스레드에서 실행하여, 주 스레드가 차단되지 않고 사용자에게 더 빠른 응답을 제공할 수 있습니다. 이 글에서는 @Async 어노테이션의 사용법과 적용 사례, 발생할 수 있는 에러 및 해결 방법에 대해 깊이 있게 설명하겠습니다.

1. 비동기 프로그래밍의 필요성

비동기 프로그래밍은 애플리케이션이 여러 작업을 동시에 처리할 수 있도록 하여, 사용자가 기다리는 시간을 최소화하는 데 중요한 역할을 합니다. 예를 들어, 데이터베이스 쿼리나 외부 API 호출처럼 시간이 오래 걸리는 작업을 비동기로 실행하면, 주 스레드는 이러한 작업이 완료될 때까지 대기하지 않고 다른 요청을 처리할 수 있습니다.

2. Spring Boot에서 비동기 처리 설정하기

비동기 기능을 사용하기 위해서는 Spring Boot 프로젝트에 다음과 같은 설정이 필요합니다.

2.1. 의존성 추가

spring-boot-starter는 기본적으로 비동기 기능을 포함하고 있지만, 추가적으로 필요한 의존성이 있을 수 있습니다. pom.xml에 다음과 같은 의존성을 추가하세요.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>

2.2. 비동기 지원 활성화

Spring Boot에서 비동기 기능을 사용하려면 @EnableAsync 어노테이션을 사용하여 비동기 처리를 활성화해야 합니다. 이 설정은 보통 애플리케이션의 메인 클래스에 추가합니다.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

3. @Async 어노테이션 사용하기

@Async 어노테이션을 사용하여 특정 메서드를 비동기로 실행할 수 있습니다. 예를 들어, 다음은 시간이 오래 걸리는 작업을 비동기로 처리하는 예시입니다.

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyAsyncService {

@Async
public void executeAsyncTask() {
try {
// Simulate long-running task
Thread.sleep(5000);
System.out.println("Async task completed!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

위의 코드에서 executeAsyncTask() 메서드는 비동기로 실행되며, 호출 즉시 리턴됩니다. 메서드가 실행되는 동안 다른 요청을 처리할 수 있습니다.

4. 비동기 메서드 호출

이제 비동기 메서드를 호출하는 방법을 살펴보겠습니다. 보통 비동기 메서드는 서비스 클래스에서 호출됩니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

@Autowired
private MyAsyncService myAsyncService;

@GetMapping("/startAsync")
public String startAsync() {
myAsyncService.executeAsyncTask();
return "Async task started!";
}
}

사용자가 /startAsync 엔드포인트에 요청을 보내면, executeAsyncTask() 메서드가 비동기로 실행되며, 즉시 "Async task started!"라는 메시지가 응답됩니다.

5. 에러 처리 및 주의사항

비동기 작업을 처리할 때는 몇 가지 에러가 발생할 수 있습니다. 예를 들어, 메서드의 반환 타입이 void가 아닌 경우, CompletableFuture를 사용할 수 있습니다.

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
@EnableAsync
public class MyAsyncService {

@Async
public CompletableFuture<String> executeAsyncTask() {
try {
Thread.sleep(5000);
return CompletableFuture.completedFuture("Async task completed!");
} catch (InterruptedException e) {
return CompletableFuture.completedFuture("Error occurred!");
}
}
}

이 경우 호출하는 측에서는 CompletableFuture를 사용하여 결과를 받을 수 있습니다.

6. 비동기 메서드의 호출 순서 및 결과

비동기 메서드는 호출한 순서와는 관계없이 실행되기 때문에, 결과를 기다리지 않고 다음 작업을 수행할 수 있습니다. 아래와 같이 결과를 기다리려면 CompletableFuture를 사용합니다.

@GetMapping("/startAsyncWithResult")
public String startAsyncWithResult() {
CompletableFuture<String> future = myAsyncService.executeAsyncTask();
future.thenAccept(result -> System.out.println("Result: " + result));
return "Async task started!";
}

이렇게 하면 비동기 작업이 완료된 후 결과를 처리할 수 있습니다.

참고 문서

이제 @Async 어노테이션을 사용하여 Spring Boot에서 비동기 프로그래밍을 활용하는 방법에 대해 충분히 이해하셨기를 바랍니다. 비동기 처리로 응답성을 향상시킬 수 있는 기회를 놓치지 마세요!

반응형