【问题标题】:How to I get the value of a Mono property without calling block()?如何在不调用 block() 的情况下获取 Mono 属性的值?
【发布时间】:2021-01-05 15:14:31
【问题描述】:

我使用此方法保存或更新数据库中的现有配方,如果配方是新的,传入对象可能没有 id 属性。将命令保存到数据库后,我需要将用户重定向到显示配方的页面,为此我需要从 recipeService.saveRecipeCommand() 返回的 Mono 中获取 id 属性。如何在不调用 .block() 方法的情况下获取此值?

@PostMapping("recipe")
public String saveOrUpdate(@ModelAttribute("recipe") RecipeCommand command) {        
    RecipeCommand savedCommand = recipeService.saveRecipeCommand(command).block();
    return "redirect:/recipe/" + command.getId() + "/show";
}

我得到的错误是:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2

【问题讨论】:

  • 你能订阅那个对象吗?

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


【解决方案1】:

我认为你应该尝试像这样返回修改后的 Mono:

return recipeService.saveRecipeCommand(command).map(command -> "redirect:/recipe/" + command.getId() + "/show");

我不确定语法,但您应该让框架解开 Mono 的结果。

【讨论】:

  • @Mouhieddine 这对你有帮助吗?
【解决方案2】:

我解决了这个问题。这是解决方案

  @PostMapping("recipe")
      public Mono<String> saveOrUpdate(@ModelAttribute("recipe") Mono<RecipeCommand> command) {
        return command.flatMap(
                recipeCommand -> recipeService.saveRecipeCommand(recipeCommand)
                        .flatMap(recipeSaved -> Mono.just("redirect:/recipe/" + recipeSaved.getId() + "/show"))
        );
      }

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2020-03-05
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多