Spring Webflux throws a “block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2”

人盡茶涼 提交于 2021-01-29 16:10:21

问题


I have a small issue with doing a blocking operation in Spring Webflux. I retrieve a list of article documents and from the list of article documents, i would like to update another object.

When i execute the below, sometimes it works and sometimes it throws a "block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2". Could you please suggest how to fix. I dont really want to make it blocking but not sure how to proceed. There are similar threads in stackoverflow but not with respective to my requirement.

It would be really nice if someone could suggest a way to work around ?

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();
}

回答1:


It has to be something like this. Please take note that I have not tested it on my IDE. To modify anything please comment and figure it out together.

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();
}

Remember, you have to put everything under chaining. that's why you have to return Mono<OrderInfo> instead of OrderInfo from setPrices method. If you find my suggested code is tough to adapt to your current coding structure, you can show me the full code. Let's find out we can build a good chain or not.

BTW, you were using getArticleDocuments(orderInfo).block();. See? you were using .block()? Don't do that in a chain. don't ever block anything in a request to the response chain process. you will return mono or flux from the controller and everything will be handled by webflux



来源:https://stackoverflow.com/questions/61275027/spring-webflux-throws-a-block-blockfirst-blocklast-are-blocking-which-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!