[PF/PlayAsset] WebFlux Functional Endpoints (Router-Handler) 구성 및 샘플코드

2023. 2. 27. 00:02
728x90
반응형

2023.02.07

개발환경구성

- FE: React-Native

- BE: WebFlux

- DB: MySQL, Redis

- IDE: Android Studio, SpringBoot(2.7.3)

- JDK: 11

- SERVER: AWS

 

 

Handler 기반 방식

1) URI 요청을 받는 Router와 로직 및 서비스 호출 등 SpringMVC 2Model 컨트롤러 역할을 하는 Handler로 구성된다.

2) Handler와 Router는 Application.java와 같은 패키지안에 포함되어야 한다.

3) GET/POST 처리는 Router에서 처리한다.

 

 

WebFlux Router

샘플코드

package com.assetinfo.playasset.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.context.ApplicationContextAware;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * @Desc
 * url 요청에 대해 handler mapping을 정의한다.
 */
@Configuration
public class RoutsConfig implements ApplicationContextAware, WebFluxConfigurer {

    ApplicationContext context;

    /**
     * @Desc    .GET/.POST 메소드를 사용해서 HTTP Response 방식을 정의
     * @param   handler
     * @return  
     */
    @Bean
    public RouterFunction<ServerResponse> route(Handler handler) {
        return RouterFunctions.route()
                .GET("/hello", handler::getHello)
                .POST("/hello", handler::postHello)
                .build();
    }
}

1) RouterFunction을 SpringBean으로 생성한다. (SpringMVC 2Model에서 BeanFactory를 등록하는 것과 같음)

2) 위의 샘플코드는 uri:port/hello 에 대한 GET/POST 요청에 대한 처리를 작성한 것이다.

3) 파라미터로 받은 Handler 객체는 Router에서 받은 요청을 처리할 객체이며 개발자가 직접 생성하는 것이다.

4) .GET() 메소드는 Handler객체의 getHello 메소드를 호출하도록 작성되어있다. (.POST()도 같은 구조)

5) .build() 메소드로 패턴을 완성시킨 후 리턴한다.

 

출처: https://www.baeldung.com/spring-5-functional-web

 

 

Webflux Handler

package com.assetinfo.playasset.handler;

import java.util.HashMap;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import lombok.NonNull;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @Desc
 * Router에 정의된 URL과 매핑된 메소드명을 Handler 메소드로 작성
 */
@Component
public class Handler {
    public Mono<ServerResponse> hello(ServerRequest request) {
        private HashMap<Object, Object> result = new HashMap<>();
        private Mono<HashMap<Object, Object>> mapper = Mono.just(result);

        List<Map> movies = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, String> temp = new HashMap<>();
            temp.put("id", Integer.toString(i));
            temp.put("title", "title" + Integer.toString(i));
            movies.add(temp);
        }
        result.put("movies", movies);
        result.put("text", "webFlux");
        mapper.subscribe((arg) -> {
            System.out.println(arg);
        });

        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromProducer(mapper, HashMap.class));
    }
}

1) 위의 샘플코드는 Router에서 받은 요청을 Handler에서 값을 만들어 JSON타입으로 리턴하는 샘플코드이다.

2) @Component 어노테이션을 클래스에 사용해 Handler로 사용할 수 있도록 만든다.

3) ServerResponse.ok().contentType() 메소드의 파라미터에 리턴받고 싶은 타입을 적어준다.

4) .body(BodyInserters.fromProducer() 메소드의 파라미터에는 리턴할 값과 리턴되는 값의 타입을 적어준다.

 

 

관련 포스트

 

[PF/PlayAsset] WebFlux개요(2)

2023.02.19 이전 포스팅 [PF/PlayAsset] WebFlux개요 1 2023.02.05 개발환경구성 - FE: React-Native - BE: WebFlux - DB: MySQL, Redis - IDE: Android Studio, SpringBoot(2.7.3) - JDK: 11 - SERVER: AWS Spring WebFlux 스프링 웹플럭스는 스프링

limreus.tistory.com

 

 

[PF/PlayAsset] WebFlux R2dbc MySQL SELECT 구현 및 샘플코드

2023.03.06 개발환경구성 - FE: React-Native - BE: WebFlux - DB: MySQL, Redis - IDE: Android Studio, SpringBoot(2.7.3) - JDK: 11 - SERVER: AWS Entity import java.sql.Date; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data;

limreus.tistory.com

 

728x90
반응형

BELATED ARTICLES

more