반응형

웹플럭스 비동기는 어떻게 지원한다는걸까? 

 

웹플럭스에서 비동기 방식을 지원하는 것은 Reactive Streams API를 사용하는 것이다.

Reactive Streams는 Publisher-Subscriber 패턴을 사용하여 비동기 데이터 처리를 지원한다.

이때 Publisher는 데이터 스트림을 생성하고, Subscriber는 해당 스트림을 구독하여 데이터를 처리하는 방식이다.

웹플럭스에서는 Flux나 Mono와 같은 Reactive Streams API를 이용하여, 데이터 처리 과정을 분할하고, 데이터를 흐름에 따라 처리한다.

이를 통해 블로킹되는 시점에서 스레드를 놓고 다른 작업을 처리할 수 있으므로, 더욱 효율적인 I/O 처리가 가능하다.

또한, 스프링 프레임워크에서는 Netty와 같은 이벤트 루프 기반의 서버를 사용하여, 논블로킹 I/O를 지원한다.

이를 통해 비동기 요청 처리와 응답 전송이 가능해지며, 높은 동시성 및 처리량을 달성할 수 있다.

따라서, 웹플럭스는 Reactive Streams API와 논블로킹 I/O를 통해 비동기 처리를 지원합니다. 순차적으로 실행되는 코드 내에서도 Publisher-Subscriber 패턴과 이벤트 루프를 이용하여, 비동기 방식의 데이터 처리가 가능해진다.

 

 

동기 vs 비동기 예제 코드

 

웹플럭스와 스프링 MVC는 모두 스프링 프레임워크에서 웹 개발을 위한 모듈이지만, 

  • 웹플럭스는 Reactive Streams API를 이용하여 비동기적인 데이터 처리를 지원하고
  • 스프링 MVC는 서블릿 API를 이용하여 데이터 처리를 지원한다.

이러한 차이점으로 인해, 두 모듈은 동작 방식이 다르며 아래 예제를 통해 확인해보자

 

[ 스프링 MVC ]

@RestController
@RequestMapping("/example")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;

    @GetMapping("/{id}")
    public String getExample(@PathVariable Long id) {
        Example example = exampleService.getExampleById(id);
        return example.toString();
    }

    @PostMapping("/")
    public String createExample(@RequestBody Example example) {
        exampleService.createExample(example);
        return "Example created successfully!";
    }
}

위 코드는 스프링 MVC에서 예제 데이터를 조회하고 생성하는 API를 구현한 예제이다.

 

getExample 메소드는 GET 요청이 들어오면, exampleService.getExampleById 메소드를 실행하여, 데이터를 조회하고 반환한다.

 

createExample 메소드는 POST 요청이 들어오면, 요청 바디에서 받은 데이터를 exampleService.createExample 메소드를 실행하여, DB에 저장한다.

 

 

[ 웹플럭스 ]

@Configuration
public class ExampleRouterConfig {

    @Bean
    public RouterFunction<ServerResponse> exampleRoute(ExampleHandler exampleHandler) {
        return RouterFunctions.route()
            .GET("/example/{id}", exampleHandler::getExample)
            .POST("/example", exampleHandler::createExample);
    }
}

@Component
public class ExampleHandler {

    @Autowired
    private ExampleService exampleService;

    public Mono<ServerResponse> getExample(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        Mono<Example> exampleMono = Mono.fromCallable(() -> exampleService.getExampleById(id));
        return exampleMono.flatMap(example -> ServerResponse.ok().bodyValue(example.toString()));
    }

    public Mono<ServerResponse> createExample(ServerRequest request) {
        Mono<Example> exampleMono = request.bodyToMono(Example.class);
        return exampleMono.doOnNext(exampleService::createExample)
            .flatMap(example -> ServerResponse.ok().bodyValue("Example created successfully!"));
    }
}

위 코드는 웹플럭스에서 예제 데이터를 조회하고 생성하는 API를 구현한 예제이다.

 

getExample 메소드는 GET 요청이 들어오면, Reactive Streams API를 이용하여 데이터를 조회한다.

 

이때 Mono.fromCallable()을 이용하여, exampleService.getExampleById 메소드를 비동기적으로 실행하고, 조회된 데이터를 Mono로 반환한다.

그리고 flatMap을 이용하여, Mono에서 조회된 데이터를 꺼내어 응답을 반환한다.

 

 

createExample 메소드는 POST 요청이 들어오면, Reactive Streams API를 이용하여 요청 바디에서 받은 데이터를 처리한다.

위 두 예제를 비교해보면,

  • 스프링 MVC 예제는 기본적으로 순차적으로 코드가 실행되며, DB 연동에 블로킹 코드가 포함되어 있다.
  • 웹플럭스 예제는 Reactive Streams API를 이용하여 비동기적인 데이터 처리를 하므로 블로킹 코드 없이 DB 연동이 가능하다.

따라서, 웹플럭스는 높은 동시성 및 처리량을 달성할 수 있으며, 대규모 데이터 처리에도 더욱 효율적이다.

반응형

'Basic > Java' 카테고리의 다른 글

EJB(Enterprise JavaBeans)란?  (0) 2023.06.12
[Spring] ClassPathResource와 classpath* 차이  (0) 2023.05.06
[WebFlux] fromFuture와 CompletableFuture  (0) 2023.03.31
[WebFlux] Mono와 Flux란  (0) 2023.03.27
build gradle Connection reset 에러  (0) 2023.03.20