8

我的应用程序中有下一个端点:

@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());
}

目前,我可以在 Postman 中将文本"data:"视为正文Content-Type →text/event-stream。据我了解Mono<ServerResponse>,总是用SSE(Server Sent Event). 是否可以在 Postman 客户端中以某种方式查看响应?

4

1 回答 1

11

您似乎在 WebFlux 中混合了注释模型和功能模型。该类ServerResponse是功能模型的一部分。

以下是如何在 WebFlux 中编写带注释的端点:

@RestController
public class HomeController {

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

这是现在的功能方式:

@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);
    }

}
于 2017-09-05T08:36:14.397 回答