Spring mvc 如何退回单声道<;地图<;串,通量<;整数>&燃气轮机&燃气轮机;春天的反应?

Spring mvc 如何退回单声道<;地图<;串,通量<;整数>&燃气轮机&燃气轮机;春天的反应?,spring-mvc,spring-boot,reactive-programming,spring-webflux,project-reactor,Spring Mvc,Spring Boot,Reactive Programming,Spring Webflux,Project Reactor,所以现在,我返回一个如下的响应 @GetMapping("/integers") @ResponseStatus(code = HttpStatus.OK) public Mono<Map<String, Flux<Integer>>> getIntegers() { Mono<Map<String, Flux<Integer>>> integers =

所以现在,我返回一个如下的响应

    @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;
    }

我希望它也能流式传输
通量
部分,但它没有。在SpringWebFlux中我将如何做到这一点?

SpringWebFlux只能处理一种被动类型,而不会处理嵌套的被动类型(如
Mono
)。控制器方法可以返回一个
Mono
、一个
Flux
、一个
ResponseEntity
、一个
Mono
,等等,但不能嵌套反应类型

您在响应中看到的奇怪数据实际上是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;
}
@GetMapping(“/integers”)
@ResponseStatus(代码=HttpStatus.OK)
公共整数(){
通量整数=integerService.getIntegers();
单结果=整数
//这将缓冲并收集单声道中的所有整数
.LIST()
//然后,我们可以将其映射并将其包装成一张地图
.map(list->Collections.singletonMap(“Integers”,list));
返回结果;
}

您可以在中阅读有关支持的返回值的更多信息。

我明白了,我最终链接了@Getmapping以生成MediaType.APPLICATION\u STREAM\u JSON\u值,因为我不确定返回纯流量是否会将数据流传输到客户端,而不会进行任何缓冲。很大程度上,由于我在您的例子中返回了10亿个重对象(integer只是实际业务对象的占位符),integers.collectToList()是否会抛出堆外内存异常,如果Flux integers有很多东西要流抱歉,编辑了上面的注释。在写任何东西之前,我不小心按下了enter键。哈,我经常用这么多评论来解决这个问题。你说得对。在这种情况下,流式传输值是正确的选择-
Flux。collectList
会缓冲内存中的所有内容,因此这不是大型集合/对象的最佳选择。呵呵,我注意到你在spring webflux上遇到了很多与此相关的问题,所以你的手现在一定很高兴,这是有意义的,谢谢!
@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;
}