【问题标题】:Iterate Flux and concat with Mono in Spring Boot在 Spring Boot 中使用 Mono 迭代 Flux 和 concat
【发布时间】:2022-01-22 15:17:42
【问题描述】:

我确实有一个 fetchEmployment() 方法可以成功获取记录,我正在迭代它以根据成功返回对象的工作人员 ID 获取 Mono 对象,但我无法创建最终的Flux,它应该由WorkerDTO(普通Spring Boot应用程序的WorkerDTO列表)组成,但它返回空对象,即@987654323 @。

@Override
public Flux<WorkerDTO> method() {
    Flux<EmployeeDTO> employmentDTOFlux = fetchEmployment();
    Flux<WorkerDTO> workerDTOFlux = Flux.empty();

    employmentDTOFlux.flatMap(employmentDTO -> {
        Mono<WorkerDTO> worker = workerService.findWorkerById(employmentDTO.getWorkerId());
        return Flux.concat(workerDTOFlux, Flux.from(worker));
    });

    return workerDTOFlux;
}

【问题讨论】:

  • 你的 workerDTOFlux 是 Flux.empty() 并且你永远不会重新分配值,即你得到一个空数组。
  • 你在flatMap那里尝试的任何东西都是没有意义的。
  • employmentDTOFlux.flatMap 永远不会被执行,因为它永远不会被订阅,另见stackoverflow.com/questions/70569881/…
  • 你好@adnan_e,你能建议我应该改变什么吗?

标签: java spring spring-boot spring-webflux


【解决方案1】:

以下内容更简单,应该可以按预期工作:

@Override
public Flux<WorkerDTO> method() {
    return fetchEmployment().flatMap(employmentDTO -> {
        workerService.findWorkerById(employmentDTO.getWorkerId());
    });
}

【讨论】:

【解决方案2】:

我认为您可以将其重写为以下简单的内容:

return fetchEmployment()
       .map(EmployeeDTO::getWorkerId)
       .flatMap(workerService::findWorkerById);

【讨论】:

  • 感谢@Thomas 的快速回答。我已根据您的回答进行了更改,我必须将方法的返回类型从Flux&lt;WorkerDTO&gt; 更改为Flux&lt;Mono&lt;WorkerDTO&gt;&gt;,当我执行该方法时,它确实会抛出ttpMessageNotWritableException: No Encoder for [reactor.core.publisher.Mono&lt;com.xyz.dto.WorkerDTO&gt;] with preset Content-Type 'null'"
  • 如果您将通量直接返回到您的端点,例如,如果使用 @RequestMapping 映射,您可能没有提供 RequestMapping.produces 来告诉 Spring 要转换的内容类型。以stackoverflow.com/questions/55355774/… 为例。
  • 使用flatMap 来“展平”从findWorkerById 返回的Monos,从而避免更改返回类型的需要,请参阅我编辑的答案。
猜你喜欢
  • 2021-09-30
  • 2018-12-12
  • 2018-03-26
  • 2019-05-18
  • 2020-01-22
  • 2019-01-20
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
相关资源
最近更新 更多