When using WebClient to call microservices in SpringCloud projects, it involves configuring WebClient, initiating get and post requests, such as request header settings, service address configuration, data conversion processing, exception processing, etc., to avoid using WebClient requests, path setting details, and data return processing techniques in loops. This article aims to help understand and apply WebClient to make microservice calls.
Configure WebClient
First, we configure WebClient in the SpringCloud project, as follows:
@Component public class WebClientConfig { @Bean @LoadBalanced public webClientBuilder() { return (); } }
Then quote in the method:
@Resource private webClientBuilder;
Calling the microservice interface
The microservice interface data is requested mainly around get and post requests, as follows:
1. Get request
public Mono<FileShare> getSharedFriends(String fileId, LoginUser loginUser) { try { ObjectMapper mapper = new ObjectMapper(); String userJson = (loginUser); WebClient webClient = ("http://space-service").build(); return () .uri(uriBuilder -> uriBuilder // Note: http://space-service cannot be added in the path, it should be added above .path("/crud/file/getSharedFriends") .queryParam("fileId", fileId) .build()) // Pass user information to downstream interfaces .header(, userJson) .retrieve() .bodyToMono(new ParameterizedTypeReference<ResultSuccess<Object>>() {}) .flatMap(resultSuccess -> { ("resultSuccess={}", (resultSuccess)); if (resultSuccess == null || () == null) { ("Received null data from server"); return (); // Avoid NullPointerException } ("()={}", ()); ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper FileShare fileShare = ((), ); return (fileShare); }) .onErrorResume(e -> { ("Error retrieving FileShare: {}", ()); return (); }); } catch (Exception ex) { ("getSharedFriends Exception ={}", ()); return (); } }
Explain the above code:
- We add a request header to the header, which contains user information and data to pass it to the downstream interface
- Set the service address in
- Use bodyToMono to convert the returned data, of course you can write your own type or
- flatMap processes the converted data and returns
- If an exception occurs, use onErrorResume to handle it.
- queryParam add? Request parameters
Then we can process the data returned by the interface
Mono<FileShare> fs = (fileId, loginUser); return ((() -> { // Return an empty FileShare object to keep the type consistent FileShare emptyFileShare = new FileShare(); // Or set the appropriate default value according to your needs return (emptyFileShare); // Return type is Mono<FileShare> }) ).flatMap(fileShare -> { ("fileShare = {}", fileShare); List<String> uids = new ArrayList<>(); List<User> user; (()); if (fileShare == null || () == null || ().isEmpty()) { user = (uids, userName, 5); return ((new ResultSuccess<>(user))); } else { (()); user = (uids, userName, 5); } return ((new ResultSuccess<>(user))); });
Note: If the webclient method returns (), it will not enter the flatMap method, so we set a value by default in the switchIfEmpty method.
The flatMap above processes the interface data you return, so that the Get request example is completed. Let’s take a look at the Post request.
2. Post request
Like Get, the code is as follows:
public Mono<List<NotifyRemind>> queryNotifyBy(LoginUser loginUser, String senderId, String objId, List<String> recipientIds) { try { ObjectMapper mapper = new ObjectMapper(); NotifyRemindRequest notifyRemindRequest = new NotifyRemindRequest(); (senderId); (objId); (recipientIds); String userJson = (loginUser); WebClient webClient = ("http://notify-service").build(); return () .uri(uriBuilder -> uriBuilder // Note: http://space-service cannot be added in the path, it should be added above .path("/crud/remind/queryBy") .build()) .bodyValue(notifyRemindRequest) // Pass user information to downstream interfaces .header(, userJson) .retrieve() .bodyToMono(new ParameterizedTypeReference<ResultInfo<Object>>() {}) .flatMap(resultInfo -> { ("resultSuccess={}", (resultInfo)); if (resultInfo == null || () == null) { List<NotifyRemind> empty = new ArrayList<>(); ("Received null data from server"); return (empty); // Avoid NullPointerException } ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper // Use TypeReference to specify the target type List<NotifyRemind> notifyReminds = ( //Note: Do not use it, because the returned List<LinkedHashMap> is changed to: new TypeReference<>() {} (), new TypeReference<>() {}); return (notifyReminds); }) .onErrorResume(e -> { ("Error retrieving FileShare: {}", ()); return (); }); } catch (Exception ex) { ("getSharedFriends Exception ={}", ()); return (); } }
Except for bodyValue adding request parameter class, other things are similar to Get requests, but there is a point to note:
When converting to the List<NotifyRemind> type you want
Please use:
((), new TypeReference<>() {})
Do not use:
((), )
Then we receive the returned interface data in the Controller layer:
Mono<List<NotifyRemind>> listMono = (loginUser, (), fileId, fids); (res -> { ("result:{}", res); if (()) { for (String fid : fids) { sendNotify(loginUser, file, fid); } } else { // Find the value that does not exist in fids List<String> missingIds = () .filter(fid -> ().noneMatch(recipient -> ().equals(fid))) .collect(()); for (String fid : missingIds) { sendNotify(loginUser, file, fid); } } });
Notice
1. If you don't use Mono, it will not request interfaces, such as:
Mono<FileShare> fs = (fileId, loginUser);
This code will not request the interface, and only if the above .flatMap is added, it will request normally
2. Do not put WebClient requests into loops, such as while and for
3. path is the path, the service name needs to beSettings in
4. Because I don't want to return data, I use.subscribe
Method to receive
Summarize
This is the article about using webclient (get and post) to request microservice interface data in SpringCloud. For more related content on calling microservices with webclient in SpringCloud, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!