Spring WebFlux

gyubong park·2020년 11월 30일
0

Spring 5.0 WebFlux란

구 Spring-Web-Reactive

용도

비동기-논블럭킹 리액티브 개발에 사용 - 적은 쓰레드로 많은 리퀘스트를 처리...
서비스간 호출이 많은 마이크로서비스 아키텍처에 적합

개발방법

기존의 @MVC 방식 - @Controller, @RestController, @RequestMapping
새로운 함수형 모델 - RouterFunction, HandlerFunction (@ 의지 없이 함수형 정의)

새로운 요청-응답 모델

서블릿 스택과 API에서 탈피
- 서블릿 API는 리액티브 함수형 스타일에 적합하지 않음
HttpServletRequest, HttpServletResponse
ServerRequest, ServerResponse

지원 웹 서버/컨테이너

Servlet 3.1+
Netty
Undertow

RouterFunction + HandlerFunction 함수형 스타일 WebFlux

스프링이 웹 요청을 처리하는 방식
- 요청 매핑
- 요청 바인딩
- 핸들러 실행
- 핸들러 결과 처리(응답 생성)

@RestController
public class MyController{
	@GetMapping("/hello/{name}") // 요청 매핑
    String hello(@PathVariable String name){ // 요청 바인딩
    	return "Hello " + name; // 핸들러 실행
    }
}

RouterFunction
함수형 스타일의 요청 매핑

@FunctionalInterface
public interface RouterFunction<T extends ServerResponse> {
	Mono<HandlerFunction<T>> route(ServerRequest request);
}

HandlerFunction
함수형 스타일의 웹 핸들러(컨트롤러 메소드)
웹 요청을 받아 웹 응답을 돌려주는 함수

함수형 WebFlux가 웹 요청을 처리하는 방식
- 요청 매핑 : RouterFunction
- 요청 바인딩 : HandlerFunction
- 핸들러 실행 :
- 핸들러 결과 처리 :

Spring MVC code

@RestController
public class MyController{
	@GetMapping("/hello/{name}") // 요청 매핑
    String hello(@PathVariable String name){ // 요청 바인딩
    	return "Hello " + name; // 핸들러 실행
    }
}

Spring WebFux code

HandlerFunction helloHandler = req -> {
	String name = req.pathVariable("name");
    Mono<String> result = Mono.just("Hello " + name);
    Mono<ServerResponse> res = ServerResponse.ok().body(result, String.class);
    
    return res;
}

RouterFunction router = req -> RequestPredicates.path("/hello/{name}").test(req)?
						Mono.just(helloHandler) : Mono.empty();
RounterFunction router = 
	RouterFunctions.route(RequestPredicates.path("/hello/{name}"),
    					  req -> ServerResponse.ok().body(fromObject("Hello " + req.pathVariable("name"))));
                            
@Bean
RouterFunction helloPathVarRouter(){
	return route(RequestPredicates.path("/hello/{name}"),
    			 req -> ServerResponse.ok().body(fromObject("Hello " + req.pathVariable("name"))));
}

M5+
리액티브 프로그래밍이란 무엇인가?
클라우드에서 리액티브 시스템 구축
Reactor, RxJava 사용법

profile
초보 개발자

1개의 댓글

comment-user-thumbnail
2020년 12월 5일

spring말고 summer은 없나요?

답글 달기