자바칩
[Spring] Spring Boot에서 동시성 처리 방법 본문
728x90
Python FastAPI vs Java Spring Boot의 동시성 모델 차이를 짚고 들어가자.
Spring Boot에서도 비동기 처리(동시성)는 가능한데, 약간의 설정 + 구조 차이가 있다.
✅ Spring Boot에서 동시성 처리 방법
1. 기본 구조: @RestController + 비동기 서비스 (@Async)
Spring은 기본적으로 스레드 기반 동시성 모델이다.
비동기를 하려면 @Async를 써서 새로운 스레드에서 처리하게 할 수 있다.
📌 예시: Spring Boot에서 @Async 기반 비동기 API
// 1. 비동기 서비스 정의
@Service
public class OperationRecordService {
@Async // 비동기 실행
public CompletableFuture<List<OperationRecord>> getRecordsByWriter(String writerId) {
// 실제 DB 호출 (예: JPA, MyBatis 등)
List<OperationRecord> records = repository.findByWriterId(writerId);
return CompletableFuture.completedFuture(records);
}
}
// 2. 컨트롤러에서 비동기 호출
@RestController
@RequestMapping("/v1/operation-records")
public class OperationRecordController {
private final OperationRecordService service;
public OperationRecordController(OperationRecordService service) {
this.service = service;
}
@GetMapping
public CompletableFuture<ResponseEntity<?>> getRecords(
@RequestParam("writer-id") String writerId
) {
return service.getRecordsByWriter(writerId)
.thenApply(records -> ResponseEntity.ok().body(records));
}
}
🛠️ 추가 설정: @EnableAsync 활성화 필요
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
🧠 동작 흐름:
- 요청이 들어옴 → Controller에서 CompletableFuture 반환
- @Async로 선언된 서비스 메서드는 별도 스레드 풀에서 처리
- 클라이언트는 결과를 기다리지 않고 응답 흐름을 비동기로 처리 가능
🆚 FastAPI vs Spring Boot 동시성 차이 요약
항목 | FastAPI | Spring Boot |
동시성 모델 | 비동기 (async/await, coroutine) | 멀티스레드 (ThreadPool + Future) |
설정 필요 여부 | 없음 (기본 async 지원) | @EnableAsync 필요 |
병렬 처리 방식 | 이벤트 루프 기반 | 스레드 풀 기반 |
복잡한 비동기 처리 | asyncio + TaskGroup | CompletableFuture, @Async, Reactor |
✅ 정리
Spring Boot에서도 @Async + CompletableFuture 조합으로 FastAPI처럼 동시성 처리 가능!
단, 기본은 동기/블로킹이라 비동기 의도는 명시적으로 설정해야 함.
'Study' 카테고리의 다른 글
FastAPI vs Spring Boot (1) | 2025.04.15 |
---|---|
비동기(Asynchronous) vs 멀티스레드(Multi-threading) (0) | 2025.04.15 |
[FastAPI] async + await 구조가 동시성에 강한 이유 (0) | 2025.04.15 |
RDBMS 용어와 NoSQL 용어 비교 (0) | 2025.04.02 |
[Flask] json.dumps() vs jsonify() (0) | 2025.03.31 |