“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Webclient usage scenarios

Introduces what is in front of the block, non-blocking, as well as the corresponding client libraries, non-blocking in high concurrency, under the condition of insufficient memory, is also a good choice, when the visitor’s service response is slow, or in the request each other, not very want to know each other the results returned, can use Webclient to non-blocking request. This is followed by how the non-blocking client library Webclient implements add, delete, change and query.

RestFul request of Webclient

RESTful style and HTTP Method

For those familiar with RESTful apis, you should know that HTTP method is used to express operations on resources.

Common HTTP methods RESTful style semantics (operations)
POST Add and submit data
DELETE Delete the data
PUT Update and modify data
GET Query and obtain data

Let’s look at how these resource scenarios can be used.

POST

POST and other common methods are as follows:

  • Block () blocks the method that gets the result of the response
  • Subscribe () non-blocking asynchronous result subscription method
  • Retrieve () obtains the BODY of the HTTP response. Exchange () can obtain HTTP packet information such as HTTP status code, headers and cookies in addition to the body of the HTTP response.
  • Mono is used to receive response results from a single object, and Flux is used to receive response results from a collection class object.
  • Placeholder syntax parameter transfer mode

Simulate form submission data

public void testFormSubmit() {

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("username", "damoin");
    map.add("UID", "11024319902323");

    Mono<String> mono = webClientBuilder.build().post()
                    .uri("http://rest-service-service/add")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .body(BodyInserters.fromFormData(map))
                    .retrieve()
                    .bodyToMono(String.class);

    System.out.println(mono.block());
}
Copy the code

As shown above, when submitting the form, we need to specify the form data type and the specific data of the form. We know: Common form data exists in the form of map. In order to obtain the response return after the request, the Retrieve function can be used. Meanwhile, Mono can be used to perform type conversion on the returned result. At the same time, if you want to block the return information, you can use the block function to handle it.

Transport objects are sent as JSON data
public void testPostJson() {
    SysUser user = new SysUser();
    user.setRealName("dwdwdww");
    user.setPhone("32323232");
    Mono<String> mono = webClientBuilder.build()
                    .post()
                    .uri("http://rest-service-service/add")
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue(user)
                    .retrieve()
                    .bodyToMono(String.class);

    System.out.println(mono.block());
    }
Copy the code

In this case, the data will be sent to the other party in Json format, also need to specify the data type MediaType.APPLICATION_JSON, other functions are the same as above.

Simulate sending JSON string data to the server

What if, instead of a JSON object, you need a JSON string?

public void testPostJsonStr() { String jsonStr = "{\"realName\": \"damon\",\"phone\": \"32323232\"}"; Mono<String> mono = webClientBuilder.build().post() .uri("http://rest-service-service/add") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(jsonStr)) .retrieve() .bodyToMono(String.class); System.out.println(mono.block()); }Copy the code

In this case, the data type is again MediaType.APPLICATION_JSON, but a JSON string is transmitted.

DELETE

To DELETE an existing resource, use the DELETE () method of webClient. This method sends an HTTP DELETE method request to the resource represented by the URL:

public void testDelete()  {
  webClientBuilder.build()
  .delete()
  .uri("http://rest-service-service/1");
}
Copy the code

PUT

To modify an existing resource, use webClient’s PUT () method. This method sends an HTTP PUT method request to the resource represented by the URL:

public void testPut() {
        SysUser user = new SysUser();
        user.setRealName("dwdwdww");
        user.setPhone("32323232");

        Mono<String> mono = webClientBuilder.build()
                        .put()
                        .uri("http://rest-service-service/1")
                        .contentType(MediaType.APPLICATION_JSON)
                        .bodyValue(user).retrieve().bodyToMono(String.class);

        System.out.println(mono.block());
}
Copy the code

The modification is sent in the format of JSON data. After the modification is complete, the modification result is returned.

GET

After adding data, we can look at the data object. If it is an object, we can use Mono:

@GetMapping(value = "/getClientResByWebClient2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Mono<String> getClientResByWebClient2() throws Exception {
             Mono<String> resp = webClientBuilder.build()
             .get()
             .uri("http://diff-ns-service-service/all/getService")
             .retrieve().bodyToMono(String.class);
             //.exchange().flatMap(clientResp -> clientResp.bodyToMono(String.class));

            resp.subscribe(body -> System.out.println(body));
            return resp;
    }
Copy the code

If there are multiple objects, it is a set set. In this case, Flux is used to obtain:

public void testFlux() { Flux<SysUser> flux = webClientBuilder.build() .get() .uri("http://diff-ns-service-service/all")  .retrieve() .bodyToFlux(SysUser.class); List<SysUser> li = flux.collectList().block(); assert li ! = null; System.out.println("li set element number: "+ li.size()); }Copy the code