如何在不调用 block() 的情况下获取 Mono 属性 的值?

How to I get the value of a Mono property without calling block()?

我使用此方法保存或更新数据库中的现有配方,如果配方是新的,传入对象可能没有 ID 属性。将命令保存到数据库后,我需要将用户重定向到显示菜谱的页面,为此我需要从 recipeService.saveRecipeCommand( ).如何在不调用 .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

我认为你应该尝试 return 修改后的 Mono,如下所示:

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

我不确定语法,但你应该让框架解包 Mono.

的结果

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

  @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"))
        );
      }