How to view response from Spring 5 Reactive API in

2020-07-22 18:27发布

I have next endpoint in my application:

@GetMapping(value = "/users")
public Mono<ServerResponse> users() {
    Flux<User> flux = Flux.just(new User("id"));
    return ServerResponse.ok()
            .contentType(APPLICATION_JSON)
            .body(flux, User.class)
            .onErrorResume(CustomException.class, e -> ServerResponse.notFound().build());
}

Currently I can see text "data:" as a body and Content-Type →text/event-stream in Postman. As I understand Mono<ServerResponse> always return data with SSE(Server Sent Event). Is it possible to somehow view response in Postman client?

1条回答
倾城 Initia
2楼-- · 2020-07-22 19:15

It seems you're mixing the annotation model and the functional model in WebFlux. The ServerResponse class is part of the functional model.

Here's how to write an annotated endpoint in WebFlux:

@RestController
public class HomeController {

    @GetMapping("/test")
    public ResponseEntity serverResponseMono() {
        return ResponseEntity
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Flux.just("test"));
    }
}

Here's the functional way now:

@Component
public class UserHandler {

    public Mono<ServerResponse> findUser(ServerRequest request) {
        Flux<User> flux = Flux.just(new User("id"));
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(flux, User.class)
                .onErrorResume(CustomException.class, e -> ServerResponse.notFound().build());
    }
}

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @Bean
    public RouterFunction<ServerResponse> users(UserHandler userHandler) {
        return route(GET("/test")
                  .and(accept(MediaType.APPLICATION_JSON)), userHandler::findUser);
    }

}
查看更多
登录 后发表回答