반응형
1. 스프링 부트 프로젝트 설정
먼저, 스프링 부트 프로젝트를 생성하고 필요한 의존성을 추가합니다. Maven을 사용하는 경우 pom.xml에 다음과 같은 의존성을 추가합니다:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 비동기 작업을 위한 설정
@EnableAsync 어노테이션을 사용하여 비동기 처리를 활성화하고, ThreadPoolTaskExecutor를 정의합니다.
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // 기본 스레드 수
executor.setMaxPoolSize(10); // 최대 스레드 수
executor.setQueueCapacity(25); // 대기 큐 용량
executor.initialize();
return executor;
}
}
3. 비동기 서비스 작성
비동기 작업을 수행할 서비스 클래스를 작성합니다. @Async 어노테이션을 사용하여 비동기 메서드를 정의합니다.
java
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MyAsyncService {
@Async
public void asyncMethod(int taskId) {
System.out.println("작업 " + taskId + " 시작");
try {
Thread.sleep(2000); // 2초 대기
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("작업 " + taskId + " 완료");
}
}
4. 컨트롤러에서 비동기 메서드 호출
비동기 메서드를 호출하는 컨트롤러 클래스를 작성합니다.
java
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("/execute")
public String executeTasks() {
for (int i = 0; i < 5; i++) {
myAsyncService.asyncMethod(i); // 비동기 메서드 호출
}
return "작업이 시작되었습니다.";
}
}
5. 애플리케이션 실행
이제 애플리케이션을 실행하고 /execute 엔드포인트에 GET 요청을 보내면 비동기 작업이 시작됩니다. 각 비동기 작업은 2초 동안 대기한 후 완료 메시지를 출력합니다.
요약
- 스프링 부트에서 ExecutorService와 @Async를 사용하여 비동기 작업을 손쉽게 구현할 수 있습니다.
- ThreadPoolTaskExecutor를 통해 스레드 풀을 설정하고, 비동기 메서드를 정의하여 작업을 비동기로 실행할 수 있습니다.