【问题标题】:Nested data access calls with spring webflux-reactor使用 spring webflux-reactor 进行嵌套数据访问调用
【发布时间】:2020-06-16 08:47:07
【问题描述】:

我正在尝试使用 spring webflux/reactor 对数据库进行嵌套调用,以返回嵌套对象的 Mono(具有其角色的用户)。

场景如下:

  • 从数据库中检索具有用户名的用户行;
  • 将用户行映射到用户 POJO;
  • 通过用户 ID 检索用户的角色;
  • 将角色映射到角色列表;
  • 将映射的角色设置为用户 POJO;
  • 返回一个用户单声道。

上面的场景必须在没有阻塞的情况下完成(我知道映射是一个很小的阻塞:))。

public Mono<User> retrieveByUsername(String username)  {
    return databaseClient.execute(usersQueries.getProperty("users.select.by.username"))
            .bind("username", username.toLowerCase())
            .map((row, meta) -> UserRowMapper.mapRow(row, meta))
            // here goes nested database query to retrieve roles and set them to retrieved user 
            // and return Mono<User>
            .one();
}

提前感谢您的帮助。

【问题讨论】:

  • 使用平面地图,然后进行下一次通话

标签: spring-data spring-webflux project-reactor reactor-netty


【解决方案1】:

以下是我如何看待您的问题的解决方案:

public Mono<User> retrieveByUsername(String username) {
    Mono<User> userMono = databaseClient
            .execute(usersQueries.getProperty("users.select.by.username"))
            .<User>map((row, meta) -> UserRowMapper.mapRow(row, meta))
            .one()
            .cache();

    Flux<Role> roles = Mono
            .from(userMono)
            .flatMapMany(user -> databaseClient
                    .execute(usersQueries.getProperty("roles.select.by.user.id"))
                    .bind("userId", user.getId())
                    .<Role>map((row, meta) -> RoleRowMapper.mapRow(row, meta))
                    .all()
            );

    return Mono
            .from(userMono)
            .flatMap(user -> roles
                    .collectList()
                    .map(r -> {
                        user.setRoles(r);
                        return user;
                    })
            );
}

【讨论】:

  • 谢谢斯捷潘。这正是我所需要的。
  • 很高兴这对您有所帮助!
猜你喜欢
  • 2019-07-31
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 2019-01-03
  • 2019-02-14
  • 1970-01-01
  • 2018-06-11
相关资源
最近更新 更多