-
스프링 웹플럭스의 코루틴 지원Spring/Webflux 2024. 1. 29. 14:43
코루틴
- 코루틴(Coroutine)은 코틀린에서 비동기-논브로킹 프로그래밍을 명령어 스타일로 작성할 수 있도록 도와주는 라이브러리이다.
- 코루틴은 멀티 플랫폼을 지원하여 코틀린을 사용하는 안드로이드, 서버 등 여러 환경에서 사용할 수 있다.
- 코루틴은 일시 중단 가능한 함수(suspend function)을 통해 스레드가 실행을 잠시 중단했다가 중단한 지점부터 다시 재개(resume) 할 수 있다.
코루틴을 사용한 구조적 동시성 예시
suspend fun combineApi() = coroutineScope { val res1 = async { getApi1() } val res2 = async { getApi2() } return ApiResult ( res1.await() res2.await() ) }
리액티브가 코루틴으로 변환되는 방식
//Mono -> suspend fun handler(): Mono<Void> -> suspend fun handler() //Flux -> Flow fun handler(): Flux<T> -> fun handler(): Flow<T>
코루틴을 적용한 컨트롤러 코드
class UserController ( private val userService: UserService, private val userDetailService: UserDetailService ) { @GetMapping("/{id}") suspend fun get(@PathVariable id: Long) : User { return userService.getById(id) } @GetMapping("/users") suspend fun gets() = withContext(Dispatcher.IO) { val usersDeffered = async { userService.gets() } val userDetailsDeffered = async { userDetailService.gets() } return UserList(usersDeffered.await(), userDetailsDeffered.await()) } }
'Spring > Webflux' 카테고리의 다른 글
스프링 웹 플럭스 (Spring Webflux) (2) 2024.01.28 리액티브 프로그래밍이란 (0) 2024.01.27 Thread, Future, CompletableFuture 란 (1) 2024.01.27 토비의 봄 TV - CompletableFuture (7) (0) 2022.06.28 토비의 봄 TV - AsyncRestTemplate의 콜백 헬과 중복 작업 문제 (6) (0) 2022.06.24