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



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

@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只能处理一个反应类型,而不能处理嵌套的反应类型(如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;
}

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

最新更新