728x90

1. @EnableAsync란 무엇인가?

@EnableAsync는 Spring에서 비동기 메서드를 활성화하기 위한 애너테이션입니다. 이를 통해 특정 메서드를 별도의 스레드에서 실행하도록 지정할 수 있습니다. 기본적으로 Spring은 단일 스레드에서 동기적으로 요청을 처리하지만, @EnableAsync를 사용하면 Spring이 비동기 작업을 위한 스레드 풀을 생성하고 이를 통해 작업을 병렬 처리합니다.

 

2. 기본 설정 방법

2.1. AsyncConfig 클래스 작성

@EnableAsync는 구성 클래스에 선언하여 사용합니다. 아래는 비동기 처리를 활성화하기 위한 간단한 설정 예제입니다.

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

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);  // 기본 스레드 수
        executor.setMaxPoolSize(10); // 최대 스레드 수
        executor.setQueueCapacity(25); // 대기 중인 작업 큐의 크기
        executor.setThreadNamePrefix("AsyncExecutor-");
        executor.initialize();
        return executor;
    }
}

2.2. @Async 사용하기

@Async 애너테이션은 비동기로 실행할 메서드에 선언합니다. 해당 메서드는 별도의 스레드에서 실행됩니다.

예를 들어, 이메일을 비동기로 발송하는 기능을 구현해보겠습니다.

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

@Service
public class EmailService {

    @Async
    public void sendEmail(String recipient, String message) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

 

2.3. 비동기 메서드 호출 Controller 예제

@Async 애너테이션이 붙은 메서드는 호출 시 호출한 스레드와 별개의 스레드에서 실행됩니다. 이를 확인하기 위해 간단한 컨트롤러를 만들어보겠습니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmailController {

    private final EmailService emailService;

    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @GetMapping("/send-email")
    public String sendEmail() {
        emailService.sendEmail("user@example.com", "메일내용");
        return "메일 전송 완료";
    }
}

 

해당 컨트롤러를 호출해보면 sendEmail에서 3초 슬립을 걸어뒀지만 바로 리턴값 응답 받는걸 보실 수 있습니다.

'자바 JAVA' 카테고리의 다른 글

2. 자바 JAVA - 스트림(stream)  (0) 2023.04.05
1. 자바 JAVA - 스트림(stream)  (0) 2023.01.17
자바 JAVA - 람다 표현식  (0) 2023.01.14
자바 csv 파일쓰기 (한글깨짐 처리)  (1) 2021.09.14

+ Recent posts