[스프링] 비동기 처리 방법

이번에는 스프링 프레임워크에서 비동기 처리를 하는 방법에 대해 알아보겠습니다.

1. @Async 어노테이션

@Async 어노테이션을 사용하면 메서드가 별도의 쓰레드에서 실행될 수 있도록 허용할 수 있습니다.

예시:

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

@Service
public class MyService {
    @Async
    public void asyncMethod() {
        // 비동기로 실행될 메서드 내용
    }
}

2. DeferredResult 또는 CompletableFuture 사용

비동기 작업의 결과를 처리하기 위해 DeferredResult 또는 CompletableFuture를 사용할 수 있습니다.

예시:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class MyController {
    @GetMapping("/async")
    public DeferredResult<String> asyncEndpoint() {
        DeferredResult<String> deferredResult = new DeferredResult<>();
        // 비동기로 처리되는 작업 수행
        return deferredResult;
    }
}

3. @EnableAsync 설정

@EnableAsync 어노테이션을 사용하여 비동기 처리 기능을 활성화할 수 있습니다.

예시:

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

@Configuration
@EnableAsync
public class AppConfig {
    // 설정 내용
}

비동기 처리를 구현함에 있어서 위의 방법들은 주로 사용되며, 개발하고자 하는 시스템의 요구사항과 형태에 맞게 선택하여 적용할 수 있습니다.

더 자세한 내용은 스프링 공식 문서를 참고하실 수 있습니다.