flatMap() operator in Webclient 作者: zorth 时间: 2025-01-01 分类: 默认分类 In Spring WebClient, the `flatMap()` operator is commonly used to transform a `Mono` or `Flux` into another `Publisher` (either a `Mono` or `Flux`) and then flatten the result into a single reactive stream. This is particularly useful when you need to make a dependent asynchronous call or chain multiple WebClient calls. Here’s how you can use `flatMap()` with WebClient: ### Example Use Case Suppose you want to: 1. Make a WebClient call to fetch some data (e.g., user details). 2. Use the result of the first call to make another WebClient call (e.g., fetch user orders based on the user ID). ### Code Example ```java import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class WebClientFlatMapExample { public static void main(String[] args) { WebClient webClient = WebClient.create("https://api.example.com"); // First API call to fetch user details Mono userOrders = webClient.get() .uri("/users/{id}", 1) // Fetch user with ID 1 .retrieve() .bodyToMono(User.class) // Deserialize response to User object .flatMap(user -> { // Use the user ID to fetch orders return webClient.get() .uri("/users/{id}/orders", user.getId()) .retrieve() .bodyToMono(String.class); // Deserialize orders as a String }); // Subscribe to the result userOrders.subscribe( result -> System.out.println("User Orders: " + result), error -> System.err.println("Error: " + error.getMessage()) ); } // Example User class static class User { private int id; private String name; // Getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ``` ### Explanation 1. **First WebClient Call**: - The first call fetches a `User` object by making a GET request to `/users/{id}`. - The response is deserialized into a `User` object using `bodyToMono(User.class)`. 2. **Using `flatMap()`**: - The `flatMap()` operator is used to take the `User` object from the first call and make another WebClient call to fetch the user's orders. - The second call uses the `user.getId()` to construct the URI for fetching orders. 3. **Flattening the Result**: - The `flatMap()` ensures that the result of the second WebClient call (a `Mono`) is flattened into the reactive stream, so the final result is a single `Mono`. 4. **Subscribing to the Result**: - The `subscribe()` method is used to consume the result or handle errors. ### Key Points - Use `flatMap()` when the second operation depends on the result of the first operation. - If you don’t need to make dependent calls and just want to transform the result, use `map()` instead. - `flatMap()` is asynchronous and non-blocking, making it ideal for chaining dependent WebClient calls. 标签: none