为什么嵌套的flatmap要比没有嵌套的运行时间长得多

ukxgm1gy  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(343)

我使用webflux的webclient从远程api检索数据。
大约有1000个用户,每个人都有几个帖子,每个帖子都有多条评论。
以下是具有适当方法的端点:

GET /users
GET /users/{userId}/posts/{postId}/comments
Flux<User> getUsers() {
  return client
      .get()
      .uri("/users")
      .retrieve()
      .bodyToMono(UserResponse.class)
      .flatMapIterable(UserResponse::getData);
}

Mono<Comment> getComments(Long userId, Long postId) {
  return client
      .get()
      .uri("/users/{userId}/posts/{postId}/comments", userId, postId)
      .retrieve()
      .bodyToMono(CommentResponse.class)
      .map(CommentResponse::getData);
}

只是想知道为什么execute2()比第一个长2倍?他们不应该是一样的还是我遗漏了什么?
因为使用嵌套的flatmaps,我可以在执行结束时获得所需的所有数据,但是对于第一个,我应该使用元组通过所有操作符传递数据。

void execute1() {
  getUsers()
      .flatMap(user -> Flux.fromIterable(user.getPosts())
          .map(post -> Tuples.of(user, post)))
      .flatMap(tuple2 -> getComments(tuple2.getT1().getId(), tuple2.getT2().getId())
          .map(comment -> Tuples.of(tuple2.getT1(), tuple2.getT2(), comment)))
      .collectList()
      .block();
}

void execute2() {
  getUsers()
      .flatMap(user ->
          Flux.fromIterable(user.getPosts())
              .flatMap(post ->
                  getComments(user.getId(), post.getId())
                      .map(comment -> Tuples.of(user, post, comment))))
      .collectList()
      .block();
}

响应对象:

@Data
class UserResponse {
  private List<User> data;
}

@Data
class User {
  private long id;
  private List<Post> posts;
}

@Data
class Post {
  private long id;
  private String title;
}

@Data
class CommentResponse {
  private Comment data;
}

@Data
class Comment {
  private long id;
  private String message;
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题