代码之家  ›  专栏  ›  技术社区  ›  katiex7

如何在spring webflux中返回mono<map<string,flux<integer>>响应?

  •  1
  • katiex7  · 技术社区  · 6 年前

    所以现在,我返回的回复看起来像

        @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中我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Brian Clozel    6 年前

    spring webflux只能处理一个反应类型,不能处理嵌套的反应类型(比如 Mono<Flux<Integer>> )中。你的控制器方法可以返回 Mono<Something> ,一个 Flux<Something> ,一个 ResponseEntity<Mono<Something>> ,一个 Mono<ResponseEntity<Something>> ,等等-但从不嵌套反应类型。

    您在响应中看到的奇怪数据实际上是jackson试图序列化一个反应类型(所以您看到的是数据的承诺,而不是数据本身)。

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

    @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 是的。