如何在Mono <t>的subscription方法内进行REST API调用

时间:2019-04-09 19:08:03

标签: java spring-boot reactive-programming

我有一个带有Spring WebFlux的Spring引导应用程序。我想以非阻塞方式调用API Rest,然后在subscribe方法中调用另一个API Rest。

第一个调用执行正确,subscribe方法也执行。我的问题是在订阅中,如何请求另一个API Rest?

@Autowired
WebClient.Builder webClientBuilder;

Mono<UserRating> monoUserRating = webClientBuilder.build().get().uri("http://ratings-data-service:8083/ratingsdata/user/" + userId)             .retrieve().bodyToMono(UserRating.class);

monoUserRating.subscribe(CatalogResource::handleResponseUserRating);

private static List<CatalogItem> handleResponseUserRating(UserRating userRating) {
    System.out.println("How to call another API???");

    //this doesn't work since is not static
    Movie movie = webClientBuilder.build().get().uri("http://movie-info-service:8082/movies/"+ rating.getMovieId())
                        .retrieve().bodyToMono(Movie.class).block();

}

1 个答案:

答案 0 :(得分:0)

使用Mono.flatMap将两个异步操作link to doc绑定在一起。

@Autowired
WebClient.Builder webClientBuilder;

public void main() {
  Mono<Movie> movieMono = getUserRating(userId)
    .flatMap(userRating -> handlerUserRating(userRating));
  movieMono.subscribe(movie -> handleMovie(movie));
}

private Mono<UserRating> getUserRating(String userId) {
  return webClientBuilder.build()
    .get()
    .uri("http://ratings-data-service:8083/ratingsdata/user/" + userId)
    .retrieve()
    .bodyToMono(UserRating.class);
}

private Mono<Movie> handleUserRating(UserRating rating) {
  return webClientBuilder.build()
    .get()
    .uri("http://movie-info-service:8082/movies/"+ rating.getMovieId())
    .retrieve()
    .bodyToMono(Movie.class);
}