【问题标题】:How to convert Mono<List> object to simple List object in java?如何在 java 中将 Mono<List> 对象转换为简单的 List 对象?
【发布时间】:2020-12-30 19:54:56
【问题描述】:

我正在尝试使用 JAVA web-flux 创建一个 POST API。在此 API 中,我想创建一个字符串列表并进行数据库调用以获取 Mono&lt;List&gt; 作为响应,但是当我尝试使用 block()Mono&lt;List&gt; 转换为简单列表对象时,我得到以下响应:

{
    "code": 500,
    "message": "block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-8"
}

如何将 Mono 对象转换为简单的 List 对象?

我正在使用以下代码:

List<String> paymentInstrumentIdList = paymentInstrumentRequest.getPaymentInstruments().stream().map(PaymentInstrumentData::getPaymentInstrumentId).collect(Collectors.toList());
Mono<List<PaymentInstrument>> paymentInstrumentList = paymentInstrumentRepository.getByPartitionKey(partitionKey.toString(), DocType.PAYMENT_INSTRUMENT, paymentInstrumentIdList);
return ResponseEntity.ok(responseMapper.getResponseAsClass(graphQlQueryController.queryPaymentInstrumentsByPaymentInstrumentId(baseHeaders, personId, membershipId, paymentInstrumentList.block()), Wallet.class, "Wallet"));

【问题讨论】:

标签: java lambda reactive-programming spring-webflux


【解决方案1】:

使用 webflux 应用程序的全部目的是你不能阻止

您正在寻找的是flatMap 函数。

return paymentInstrumentRepository.getByPartitionKey(
    partitionKey.toString(), 
    DocType.PAYMENT_INSTRUMENT, paymentInstrumentIdList)
    .flatmap(list -> {
        return return ServerResponse.ok().body(responseMapper.getResponseAsClass(
    graphQlQueryController.queryPaymentInstrumentsByPaymentInstrumentId(
        baseHeaders, 
        personId, 
        membershipId, 
        list);
    };

这是 webflux 的基础知识,我建议你阅读official reactor documentation getting started,以便了解基础知识和目的。

答案是写在手机上的,未经测试。

这里也是getting started tutorial

【讨论】:

  • 在 build() 方法上出现错误 - java:找不到符号符号:方法 build() 位置:类 java.lang.object
  • 它是在移动设备上编写的,没有经过测试,所以我删除了代码,而不是用来复制和粘贴,你明白了要点,可以查看文档如何返回正确的服务器回应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多