【问题标题】:should we use exceptions in reactor mono flow to match result typings?我们应该在反应器单流中使用异常来匹配结果类型吗?
【发布时间】:2022-11-02 01:52:17
【问题描述】:

我对 mongo findOneAndUpdate 有一种奇怪的(?)方法: 如果过滤器匹配 - 然后更新,如果不匹配 - 好吧:

public Mono<Module> findOneAndUpdateNotificationDate(String moduleId, Duration frequency) {
  Bson filter = and(
    eq(ID, new ObjectId(moduleId)),
    or(
       exists(LAST_NOTIFICATION_DATE, false),
       lt(LAST_NOTIFICATION_DATE, now.minus(frequency))
    )
  );
  Bson updates = combine(
    set(LAST_NOTIFICATION_DATE, now)
  );
  return Mono.from(collection.findOneAndUpdate(filter, updates));
}

和使用它的服务:

private Mono<Boolean> maybeSendNotification(String moduleId, ModuleState state) {
  return repo.findOneAndUpdateNotificationDate(moduleId, notificationFrequency)
    .switchIfEmpty(Mono.error(new NotFoundException()))
    .flatMap(module -> notificationService.sendAlertEmail(module, moduleState))
    .onErrorResume(NotFoundException.class, e -> Mono.just(true));
  }

目标是以一些 [频率] 发送电子邮件通知。

想知道在这里使用异常的正确方法吗?以及如何正确地做到这一点而不破坏打字?

【问题讨论】:

    标签: java mongodb reactor


    【解决方案1】:

    最后,仅使用交换运算符和使用 Mono.defer 即可实现正确的行为:

    return repo.findOneAndUpdateNotificationDate(moduleId, notificationFrequency)
    .flatMap(module -> notificationService.sendAlertEmail(module, moduleState))
    .switchIfEmpty(Mono.defer(() -> Mono.just(true)));
    

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2021-06-15
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多