Responsive Programming Theory: Source Code Analysis of WebClient

1 Dependence

In the WebFlux system, how to request the interface provided by a third party or other internal sibling systems?
Of course, OKhttp/Apache HttpClient/SpringMVC RestTemplate can be used directly.
WebFlux also provides a tool for requesting interfaces: WebClient.
This article mainly explains the functions of WebClient, theoretical articles.
The practical chapter explains how to actually fight.

2 Webclient

Spring WebClient official address:
https://docs.spring.io/spring-framework/reference/web/webflux-webclient.html
insert image description here

Source code location: org.springframework.web.reactive.function.client.WebClient
Let's take a look at WebClient's comments first:
non-blocking responsive sending of HTTP requests.
Expose a reactive API through an underlying HTTP client library such as Reactor Netty.
Core points:

  • How to build an instance: through create(), create(String), builder() methods
  • How to get the response result: through retrieve(), exchangeToMono(), exchangeToFlux() method
  • How to add the request body in the request: through bodyValue(Object), body(Publisher, Class) method

Next, explain WebClient from the application point of view, namely:
create an instance -> request method -> request URI -> request body -> result analysis.

insert image description here

2.1 Build an example

There are three methods to build a WebClient instance: create(), create(String), builder().
These three static factory methods all use the default implementation class of the WebClient interface: DefaultWebClientBuilder.
The difference is that the parameters are different:

  • create(): build by default, without parameters;
  • create(String): Build the basic URL prefix, such as public IP and PORT;
  • builder(): build by default, without parameters, build a constructor;

insert image description here
After building the WebClient instance, you can initiate an HTTP/HTTPS request.
The WebClient interface is instantiated through the factory method, combined with the automatic assembly mechanism of SpringBoot.
Here, @PostConstruct is used to instantiate the WebClient when starting the SpringBoot service, and
initialize the IP and PORT of the calling interface, such as : http://192.168.0.123:8888
is prepared for subsequent use.

  • sample
    private WebClient pyRpcWebClient;

    @PostConstruct
    public void init() {
    
    
        pyRpcWebClient = WebClient.builder().baseUrl(rpcPyUrl).build();
    }

2.2 Request method

Next, look at the request methods, familiar flavors:
GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS methods.
Method list:
insert image description here
Interface method: org.springframework.web.reactive.function.client.WebClient
insert image description here
The specific implementation is in the implementation class:
org.springframework.web.reactive.function.client.DefaultWebClient
here, readers can study the details.
insert image description here

2.3 Configure URIs

After instantiating WebClient and determining the request method, the URI of the actual request interface needs to be configured next.
Method list:
insert image description here
Interface class: org.springframework.web.reactive.function.client.WebClient.UriSpec
insert image description here

Default implementation class:
org.springframework.web.reactive.function.client.DefaultWebClient.DefaultRequestBodyUriSpec
The specific source code is as follows:
insert image description here

2.4 Send request parameters

Next, build the request parameters, such as Form-Data,
the interface provided in the Body type WebClient: RequestBodySpec is used to configure the request header and request body.
Method list: divided into two categories

  • Request header: contentType, contentLength
  • Request body: body, bodyValue

Among them, body can be filled with request body, form data, or file data.
insert image description here
RequestBodySpec interface:
org.springframework.web.reactive.function.client.WebClient.RequestBodySpec
insert image description here

Default implementation:
org.springframework.web.reactive.function.client.DefaultWebClient.DefaultRequestBodyUriSpec
insert image description here

2.5 Extract the response result: retrieve()

After the WebClient requests the interface, use the retrieve() method to extract the result of the interface response.
The methods provided by ResponseSpec are as follows:
insert image description here
The retrieve type is: ResponseSpec.
This interface provides many result processing methods, such as converting the results into Mono, Flux, and Entity types,
and can obtain the corresponding response status code according to the onStatus() method for processing. .
Http status code:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

serial number status code describe
1 1xx response message
2 2xx successful response
3 3xx redirect
4 4xx The client responds abnormally
5 5xx The server responds abnormally

insert image description here
Next, analyze the ResponseSpec interface, which is a protocol for processing response results.
For example, the onStatus method processes the results according to the response status code. When an exception occurs, the corresponding processing is performed.
When it succeeds, the data flow is passed down;
bodyToMono converts the result to Mono A stream of objects, passed to the caller.
Result processing is a very important function, here is a classification explanation:

2.5.1 onStatus

onStatus: Extract the status of the current response and do corresponding processing,
HTTP response status code: 1xx/2xx/3xx/4xx/5xx,
when the response status is abnormal, such as 4xx and 5xx, you can directly make appropriate processing,
such as throwing If an exception occurs, a custom response message is returned.
insert image description here
The status code is processed through onRawStatus in onStatus, which can be viewed in DefaultWebClient.
insert image description here

The default implementation of DefaultWebClient's onStatus implementation source code is as follows.
From the source code, it can be seen that it is processed through onRawStatus.
insert image description here

2.5.2 body To Mono

When the HTTP response code is normal, the response result is processed into a custom target type through bodyToMono and packaged with Mono.
However, the response agreement between interfaces is generally determined by the interface provider first, and the caller is compatible with the agreement.
If it is within the company , it can be designed according to a unified agreement.
After bodyToMono maps the result to the agreed type, it is passed as Mono.
insert image description here

2.5.3 bodyToFlux

Same as bodyToMono function, the difference is that the response result is wrapped with Flux.
insert image description here

2.5.4 toEntity

Map the response entity with ResponseEntity and wrap it with Mono.
It can be seen from the response type: Mono<ResponseEntity<T>>.
insert image description here

2.5.5 toEntityList

Same as the toEntity function, the difference is that the response result is processed into a List format.
insert image description here

2.5.6 toEntityFlux

This is not much to explain, the same as toEntityMono.

insert image description here
So far, the response result processing method has been simplified.
Through the above knowledge, we can use the WebClient request interface and properly process the interface response result.

3 Summary

(1) WebClient request interface process: create an instance -> request method -> request URI -> request body -> result analysis; (2)
Use the interface transfer parameters: contentType, contentLength method to configure the request header; body, bodyValue method to configure the request body ;
(3) Extract the interface response result using: retrieve() method;
(4) Use the interface response status judgment: onStatus() method;
(5) Interface response result processing methods include: bodyToMoon/bodyToFlux/toEntity/toEntityFlux;

Guess you like

Origin blog.csdn.net/Xin_101/article/details/131057815