【问题标题】:Reactor Java Flux vs MonoReactor Java Flux 与 Mono
【发布时间】:2021-11-23 19:48:42
【问题描述】:

我有以下场景要实施。 通过用户ID获取作业列表,迭代作业,然后通过属性获取帐户条目,最后更新到帐户。

方法定义

Mono<Void> execute(List<String> users)

Jobs Dao 返回 Mono

Mono<List<JobInfo>> getJobsByUser(String user)
class JobInfo {
   String user;
   String account;
}

获取帐号正在返回 Mono 列表,

Mono<List<Account>> getAccounts(String account)

我正在努力使用 Mono 无阻塞方式来做到这一点。我尝试使用块来执行此操作,但得到

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-
public Mono<Void> execute(List<String> users) {
   users.forEach(user -> {
    jobDao.getJobsByUser(user).block().stream().forEach(job -> {
      accountDam.getAccounts(job.getAccount()).block().forEach(acc -> {
        // update account
      });
    });
   
   });

   return Mono.empty().then();

}

【问题讨论】:

  • I tried to use Flux and iterate users to get accounts. But method is finish executing before running this. 代码在哪里?我们不会为您编写代码并完成您的工作,这是学习经验吗?
  • @Toerktumlare 我很抱歉。我用代码更新了问题。
  • @Delantha 您的方法更具命令性而非被动性。尝试在不使用block() 方法的情况下重新实现它。这可能会对您有所帮助:projectreactor.io/docs/core/release/reference/#which-operator
  • 我建议您在询问堆栈溢出问题之前先阅读 reactor 文档中的“入门指南”。

标签: java project-reactor


【解决方案1】:

据我所知,您需要以下流程:

public Mono<Void> execute(List<String> users) {
    return Flux.fromIterable(users)
        .flatMap(user -> getJobsByUser(user))
        .flatMapIterable(jobs -> jobs)
        .flatMap(job -> accountDam.getAccounts(job.getAccount()))
        .flatMapIterable(accounts -> accounts)
        .flatMap(account -> updateAccount(account))
        .then();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 2021-06-12
    • 2020-09-25
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2020-09-14
    • 2019-12-03
    相关资源
    最近更新 更多