代码之家  ›  专栏  ›  技术社区  ›  Viraj

反应式编程如何实现相关结果

  •  0
  • Viraj  · 技术社区  · 6 年前

    我正在尝试使用spring boot使用反应模式REST服务。我已经设置了代码,它正在将项目保存到Cassandara数据库中。现在我有以下要求以反应式方式书写:

    如果在数据库中找不到项,请保存该项。如果项目存在,则引发异常。

    我一直在试图弄清楚如何以反应式的方式进行这种逻辑。由于我是这个领域的初学者,很难理解这个概念。以下是我的方法:

    @Override
    public Mono<String> createItem(ItemCreateParam itemCreateParam) {
        //This check if item exits in database.
        Mono<Boolean> byName = reactiveItemRepository.existsById(itemCreateParam.getName());
    
        //This save the item and return the id (i.e name)
        return Mono.just(itemCreateParam)
                .flatMap(item -> convert(item))
                .log()
                .flatMap(t -> reactiveTemplateRepository.save(t))
                .map(t-> t.getName());
    }
    

    如何以被动的方式将这两者结合起来?

    1 回复  |  直到 6 年前
        1
  •  1
  •   MuratOzkan    6 年前

    只需检查 existsWithId() .我将这样实施:

    @Override
    public Mono<String> createItem(ItemCreateParam itemCreateParam) {
        return reactiveItemRepository.existsById(itemCreateParam.getName())
               .doOnNext(exists -> {
                    if (exists) {
                         throw new AppException(ErrorCode.ITEM_EXISTS);
                    }
               })
              .flatMap(exists -> convert(item))
              .flatMap(converted -> reactiveTemplateRepository.save(converted))
              .map(saved -> saved.getName());
    }
    

    请注意 AppException 类型可以是任何其他类型,但它应该扩展 RuntimeException .