Requirements: In microservices architectures, calls between services often use the HTTP protocol, usually using the HttpClient class to make HTTP requests, or use itRefit.HttpClientFactory、WebApiClientCoreThird-party libraries based on HttpClient encapsulation.
For more information about using HttpClient, please refer to:The hyperlink login is visible.
HttpClient source code:The hyperlink login is visible.
In the HttpClient parameterless constructor, the HttpClientHandler object is instantiated by default, and the HttpClientHandler inherits and implements the HttpMessageHandler abstract class.Default flow: HttpClient -> HttpClientHandler -> SocketsHttpHandler -> ...
According to source code analysis, the object inherited from the HttpMessageHandler is a concrete implementation of the HttpClient sending HTTP requests. HttpClient willHttpRequestMessageThe object is passed in and then receivedHttpResponseMessageObject returns content.
Try creating a new TestHttpHandler class, inheriting the HttpMessageHandler abstraction class and implementing the SendAsync method, and then instantiating it in the HttpClient constructor, with the following code:
As shown below:
Although calling HttpClient to send a GET request, the specific implementation of the SendAsync method does not send an HTTP request, and there is no network flow, soYou can unplug the network cable and the program will work normally。
atWhen using an HttpClient object, the underlying socket is not released immediately, which can cause socket exhaustion issues. Microsoft is aware of this problem and recommends using IHttpClientFactory in ASP.NET Core projects to create HttpClient objects.IHttpClientFactory pools factory-created HttpMessageHandler instances into a pool to reduce resource consumption. When you create a new HttpClient instance, you might reuse the HttpMessageHandler instance in the pool(if the survival period has not expired).
IHttpClientFactory for .NET:The hyperlink login is visible.
ASP.NET Core has the concept of pipeline middleware,In fact, HttpClient also has the concept of pipeline middleware with the help of Delegating Handler, as shown in the figure below:
By using this feature, we can intercept requests and responses, such as increasing token authentication before requests, recording the time required for requests and responses, and wrapping response data.
Just inherit the DelegatingHandler class and override the SendAsync method.
Recording HTTP requests takes time, and the code is as follows:
Call IHttpClientFactory to create an HttpClient and send a request, as shown in the following image:
(End)
|