【问题标题】:Setting one mono within another using webflux使用 webflux 在另一个中设置一个单声道
【发布时间】:2023-03-07 02:59:01
【问题描述】:

我正在从 mongo db 中检索发布者 Mono<ProductOrder>

我有另一个发布者Mono<CommandResponse>

我想将ProductOrder 对象设置为CommandResponse,因为它是该类的一部分。喜欢commandResponse.setProductOrder(po instance)

CommandResponse 除了ProductOrder 实例之外,还将有不同的MonoString or Int

最后想返回Mono<ServerResponse>,其中包含CommandResponse的正文

我无法将Mono<ProductOrder> 对象设置为Mono<CommandResponse>

请帮忙。谢谢。


代码片段

@Component
public class Handler {


    @Autowired
    private MongoService service;

    public Mono<ServerResponse> get(ServerRequest request) {
        Mono<ProductOrder> p = service.queryById();
        
        

> Here, in the return statement i want to return Mono<CommandResponse> 
> instead of Mono<ProductOrder> in the response body
> remember: CommandResponse has a reference to ProductOrder

        return 
            ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(p, ProductOrder.class).map(null);
        );
    }
}

【问题讨论】:

  • 如果您可以添加实际代码 sn-p,您将有更好的机会获得帮助。
  • 在上面添加了代码sn-p

标签: spring mongodb spring-boot spring-webflux reactive


【解决方案1】:
Mono<CommandResponse> commandMono = ... // I don't how it is set 
Mono<ProductOrder> productMono = service.queryById();
Mono.zip(commandMono, productMono)
  .map(tuple -> { 
    var command = tuple.getT1();
    var product = tuple.getT2();
    command.setProductOrder(product) // => .setProductOrder(po instance)
    return command;
  })
  .flatMap(command -> ServerResponse.ok()
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(command)
  )

我还没有运行这段代码,所以我不确定它是否可以编译,但是有了它你应该能够弄清楚你的代码是如何工作的

【讨论】:

  • 非常感谢。 @sawim
猜你喜欢
  • 2020-08-12
  • 2019-03-05
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 2019-07-23
  • 2015-11-08
相关资源
最近更新 更多