SoFunction
Updated on 2025-03-03

Use webclient (get and post) to request microservice interface data in SpringCloud

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:

  1. We add a request header to the header, which contains user information and data to pass it to the downstream interface
  2. Set the service address in
  3. Use bodyToMono to convert the returned data, of course you can write your own type or
  4. flatMap processes the converted data and returns
  5. If an exception occurs, use onErrorResume to handle it.
  6. 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 -&gt; {
                ("fileShare = {}", fileShare);
                List&lt;String&gt; uids = new ArrayList&lt;&gt;();
                List&lt;User&gt; user;
                (());
                if (fileShare == null || () == null || ().isEmpty()) {
                    user = (uids, userName, 5);
                    return ((new ResultSuccess&lt;&gt;(user)));
                } else {
                    (());
                    user = (uids, userName, 5);
                }
                return ((new ResultSuccess&lt;&gt;(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&lt;List&lt;NotifyRemind&gt;&gt; queryNotifyBy(LoginUser loginUser, String senderId, String objId, List&lt;String&gt; 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 -&gt; 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&lt;ResultInfo&lt;Object&gt;&gt;() {})
                    .flatMap(resultInfo -&gt; {
                        ("resultSuccess={}", (resultInfo));
                        if (resultInfo == null || () == null) {
                            List&lt;NotifyRemind&gt; empty = new ArrayList&lt;&gt;();
                            ("Received null data from server");
                            return (empty);  // Avoid NullPointerException                        }
                        ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper
                        // Use TypeReference to specify the target type                        List&lt;NotifyRemind&gt; notifyReminds = (
                                //Note: Do not use it, because the returned List<LinkedHashMap> is changed to: new TypeReference<>() {}                                (), new TypeReference&lt;&gt;() {});
                        return (notifyReminds);
                    })
                    .onErrorResume(e -&gt; {
                        ("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&lt;List&lt;NotifyRemind&gt;&gt; listMono = (loginUser, (), fileId, fids);

(res -&gt; {
    ("result:{}", res);
    if (()) {
        for (String fid : fids) {
            sendNotify(loginUser, file, fid);
        }
    } else {
        // Find the value that does not exist in fids        List&lt;String&gt; missingIds = ()
                .filter(fid -&gt; ().noneMatch(recipient -&gt; ().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.subscribeMethod 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!