我如何在 Spring Webflux 中 return Mono<Map<String, Flux<Integer>>> 响应?
How can I return a Mono<Map<String, Flux<Integer>>> response in 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;
}
这给了我
的回应
{"Integers":{"scanAvailable":true,"prefetch":-1}}
我希望它也流式传输 Flux<Integer>
部分,但它没有。我如何在 Spring webflux 中执行此操作?
Spring WebFlux 只能处理一种反应类型,不会处理嵌套的反应类型(如 Mono<Flux<Integer>>
)。您的控制器方法可以 return 一个 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 中阅读有关支持的 return 值的更多信息。
所以现在,我返回的响应看起来像
@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>>
)。您的控制器方法可以 return 一个 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 中阅读有关支持的 return 值的更多信息。