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

z31licg0  于 2021-06-26  发布在  Java
关注(0)|答案(2)|浏览(1050)

我使用此方法保存或更新数据库中的现有配方,如果配方是新的,则传入对象可能没有id属性。将命令保存到db后,我需要将用户重定向到显示配方的页面,为此,我需要从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
bfrts1fy

bfrts1fy1#

我想你应该试着像这样返回修改过的mono:

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

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

irlmq6kh

irlmq6kh2#

我解决了这个问题。这就是解决办法

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

相关问题