spring-mvc - 如何在 Spring Webflux 中返回 Mono<Map<String, Flux<Integer>>> 响应?

标签 spring-mvc spring-boot reactive-programming spring-webflux project-reactor

所以现在,我正在返回一个看起来像这样的响应

    @GetMapping("/integers")
    @ResponseStatus(code = HttpStatus.OK)
    public Mono<Map<String, Flux<Integer>>> getIntegers() {
        Mono<Map<String, Flux<Integer>>> integers = 
               Mono.just(Map.of("Integers", integerService.getIntegers()));
        return integers;
    }

这给了我一个回应

{"Integers":{"scanAvailable":true,"prefetch":-1}}

我希望它播放 Flux<Integer> 的地方部分也是,但事实并非如此。我将如何在 Spring webflux 中执行此操作?

最佳答案

Spring WebFlux 只能处理一种 react 类型,不会处理嵌套的 react 类型(如 Mono<Flux<Integer>> )。您的 Controller 方法可以返回 Mono<Something> , 一个 Flux<Something> , 一个 ResponseEntity<Mono<Something>> , 一个 Mono<ResponseEntity<Something>> , 等等 - 但从来没有嵌套的 react 类型。

您在响应中看到的奇怪数据实际上是 Jackson 试图序列化 react 类型(因此您正在查看数据的 promise ,而不是数据本身)。

在这种情况下,您可以像这样重写您的方法:

@GetMapping("/integers")
@ResponseStatus(code = HttpStatus.OK)
public Mono<Map<String, Flux<Integer>>> getIntegers() {
    Flux<Integer> integers = integerService.getIntegers();
    Mono<Map<String, List<Integer>>> result = integers
            // this will buffer and collect all integers in a Mono<List<Integer>>
            .collectList()
            // we can then map that and wrap it into a Map
            .map(list -> Collections.singletonMap("Integers", list));
    return result;
}

您可以在 the Spring WebFlux reference documentation 中阅读有关支持的返回值的更多信息.

关于spring-mvc - 如何在 Spring Webflux 中返回 Mono<Map<String, Flux<Integer>>> 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51288977/

相关文章:

java - 在 Spring MVC 中选择性地绑定(bind)属性

java - 我的 Spring SecurityConfig 没有被获取

java - 重写@ConfigurationProperties

java - RxJava有没有NOP操作?

macos - Quartz Composter —重新创建Audioskop(根据音频输入调整视频时间)

java - 如何获取 :errors tag by using MultiActionController? 形式的错误消息

java - org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory' defined in ServletContext resource

java - Spring Boot 中的日志文件端点

java - SPRING BOOT 中的 POST 请求发生 I/O 错误

javascript - 组合最新运算符替代方案