所以现在,我正在返回一个看起来像这样的响应
@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/