i want to know how return a empty Mono when i use webClient, i have this code and it works when the request return a user.
public User getUserByUsername(String username) { Mono<User> user = webClient.get().uri(uriBuilder -> uriBuilder .path("localhost:8090/user" + "/getByUsername").queryParam("username", username).build()) .retrieve() .bodyToMono(User.class); User userRet = user.block(); return userRet; }
Advertisement
Answer
First of all, don’t use block()
if you really want to take full advantage of using reactive stack. With it you are blocking the thread to wait for a response, don’t do that. You must always handle Mono
and Flux
in your code instead. Something along the following lines:
public Mono<User> getUserByUsername(String username) { return webClient.get().uri(uriBuilder -> uriBuilder .path("localhost:8090/user" + "/getByUsername").queryParam("username", username).build()) .retrieve() .bodyToMono(User.class); }
You can then specify what you want to do if the response is 4XX or 5XX. Below the example for 5XX:
public Mono<User> getUserByUsername(String username) { return webClient.get().uri(uriBuilder -> uriBuilder .path("localhost:8090/user" + "/getByUsername").queryParam("username", username).build()) .retrieve() .onStatus(HttpStatus::is5xxServerError, response -> Mono.empty()) .bodyToMono(User.class); }