【问题标题】:Spring Webflux throws a "block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2"Spring Webflux 抛出“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-2 不支持”
【发布时间】:2020-04-17 15:18:29
【问题描述】:

我在 Spring Webflux 中执行阻塞操作时遇到了一个小问题。我检索了文章文档列表,并且从文章文档列表中,我想更新另一个对象。

当我执行以下操作时,有时它可以工作,有时它会抛出“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-2 不支持”。您能否建议如何解决。我真的不想让它阻塞,但不知道如何继续。 stackoverflow 中有类似的线程,但不符合我的要求。

如果有人能建议一种解决方法,那就太好了?

private OrderInfo setPrices(final OrderInfo orderInfo) {
    final List<ArticleDocument> articleDocuments = getArticleDocuments(orderInfo).block(); // Problematic line
    for (ArticleDocument article : articleDocuments) {
         //Update orderInfo based on one of the article price and few more condition.
  }
 return orderInfo;
}

private Mono<List<ArticleDocument>> getArticleDocuments(final OrderInfo orderInfo) {
    return this.articleRepository.findByArticleName(orderInfo.getArticleName()).collectList();
}

【问题讨论】:

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


    【解决方案1】:

    它必须是这样的。请注意,我没有在我的 IDE 上测试过它。要修改任何内容,请发表评论并一起解决。

    private Mono<OrderInfo> setPrices(final OrderInfo orderInfo) {
        getArticleDocuments(orderInfo)
            .map(articleDocuments -> {
                articleDocuments.forEach(article -> // UPDATE AS YOU NEED);
                return orderInfo;
            });
    
    private Mono<List<ArticleDocument>> getArticleDocuments(final OrderInfo orderInfo) {
        return this.articleRepository.findByArticleName(orderInfo.getArticleName()).collectList();
    }
    

    请记住,您必须将所有内容置于链接之下。这就是为什么您必须从 setPrices 方法返回 Mono&lt;OrderInfo&gt; 而不是 OrderInfo 的原因。如果您发现我建议的代码很难适应您当前的编码结构,您可以向我展示完整的代码。让我们看看我们能不能建立一个好的链条。

    顺便说一句,您使用的是getArticleDocuments(orderInfo).block();。看?你用的是.block()?不要在连锁店中这样做。永远不要阻止对响应链进程的请求中的任何内容。您将从控制器返回单声道或通量,一切都将由 webflux 处理

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2022-07-19
      • 2020-04-21
      • 2021-08-04
      • 2018-12-29
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 2019-07-31
      相关资源
      最近更新 更多