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

kat*_*ex7 2 spring-mvc reactive-programming spring-boot project-reactor spring-webflux

所以现在,我正在返回一个类似的响应

    @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;
    }
Run Code Online (Sandbox Code Playgroud)

这给了我一个回应

{"Integers":{"scanAvailable":true,"prefetch":-1}}
Run Code Online (Sandbox Code Playgroud)

我希望它Flux<Integer>也能播放该部分,但事实并非如此。我该如何在 Spring webflux 中做到这一点?

Bri*_*zel 6

Spring WebFlux 只能处理一种反应类型,而不能处理嵌套的反应类型(例如 a Mono<Flux<Integer>>)。您的控制器方法可以返回 a Mono<Something>、 a Flux<Something>、 a 、 ResponseEntity<Mono<Something>>aMono<ResponseEntity<Something>>等 - 但永远不会返回嵌套反应类型。

您在响应中看到的奇怪数据实际上是杰克逊试图序列化反应类型(因此您正在查看数据的承诺,而不是数据本身)。

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

@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;
}
Run Code Online (Sandbox Code Playgroud)

您可以在Spring WebFlux 参考文档中阅读有关支持的返回值的更多信息。