【问题标题】:Project Reactor conditional executionProject Reactor 条件执行
【发布时间】:2018-09-26 09:14:14
【问题描述】:

我有一个对象要保存(到 MongoDB),但在此之前我需要检查某些条件是否为真。

对象包含其他对象的 ID。好像

"object": {
   "id": "123",
   "subobject1": { "id": "1" },
   "subobject2": { "id": "2" }
}

子对象只包含id,其他信息位于其他集合中,所以我必须检查信息是否存在。

在块样式中我可以做类似的事情

    if (!languageRepository.exists(Example.of(wordSet.getNativeLanguage())).block()) {
        throw new RuntimeException("Native language doesn't exist");
    }

    if (!languageRepository.exists(Example.of(wordSet.getTargetLanguage())).block()) {
        throw new RuntimeException("Target language doesn't exist");
    }

只有这样我才能保存我的对象

return wordSetRepository.save(wordSet);

我怎样才能在不阻塞的情况下以“反应式”的方式做到这一点?

【问题讨论】:

  • languageRepository.exists、Example.of、wordSet.getTargetLanguage() - 这都是什么意思?
  • 我们去languageRepository检查nativeLanguage和targetLanguage(子对象1和子对象2)是否存在。如果它们存在于languageRepository中,我们可以将这个对象(wordSet)保存到wordSetRepository
  • wordSet 将只保存 nativeLanguage 和 targetLanguage 的 id,而不是完整的对象。完整的对象在 languageRepository 中。
  • 我的意思是,它们是什么类型的对象?使用block() 暗示languageRepository.existsMono<Boolean>。其他的呢?
  • targetLanguage 和 nativeLanguage 属于语言类型(只是一些字段和 id)。 WordSet 包含一些字段(包括 targetLanguage 和 nativeLanguage)和 id。

标签: java mongodb project-reactor reactive reactor


【解决方案1】:

如果您想针对本地语言和目标语言错误情况传播不同的错误,您需要在 flatMap 内执行异步过滤:

objectFlux.flatMap(o ->
    Mono.just(o)
        .filterWhen(languageRepository.exists(...)) //native
        .switchIfEmpty(Mono.error(new RuntimeException("Native language doesn't exist"))
        .filterWhen(languageRepository.exists(...)) //target
        .switchIfEmpty(Mono.error(new RuntimeException("Target language doesn't exist"))
    )
    .flatMap(wordSetRepository::save);

flatMap 内部的异步过滤确保如果测试未通过,则内部序列为空。这反过来又使我们能够检测案例并传播适当的错误。如果两个测试都通过,原始的o 会在主序列中传播。

第二个flatMap 从那里获取它,只接收通过两个过滤器的元素并将它们保存在数据库中。

请注意,第一个不通过过滤器的元素将中断整个序列(但在阻塞代码中它是相同的,因为抛出了异常)。

【讨论】:

  • 谢谢!还有一个问题:方法应该有 objectFlux 作为输入参数吗?我的意思是这个方法位于服务层,它只需要“对象”(没有 Mono 或 Flux)。只做“Mono.just(object)”可以吗?
  • 两者都很好,Mono.just 的典型用法是充当命令式遗留代码与升级后的响应式代码的边界处的转换方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 2022-01-02
  • 2021-05-01
  • 1970-01-01
  • 2021-07-14
  • 2021-12-22
  • 2019-05-29
相关资源
最近更新 更多