[Reserved] .net Core use IHttpClientFactory request

Address reprint: https://www.cnblogs.com/chenxi001/p/12203731.html

First, why do not HttpClient

        After 1.HttPClient when finished using does not close immediately open network resources will take up the underlying socket connection, but calls its own Dispose method in HttpClient, and the resources can not be released immediately

         2. If you frequently use HttpClient, frequently open the link, the close link consumption will be enormous.

Second, the solution

        1. HttpClient we can extend the life cycle, such as its built a static object

private static HttpClient Client = new HttpClient();

          2. Or use a singleton, as to which one you use single-case model on your own, and there will not be a fine. Because it feels not very comfortable

Three, HttpClientFactory

       1. After .NET Core 2.1 version introduced HttpClientFactory solve all the pain points of HttpClient. With HttpClientFactory, we do not need to be concerned about how to create HttpClient, and how to release it. It can be very friendly and DI container by using it in conjunction with a specific business can create HttpClient, and more flexible.

    2.HttpClientFactory created HttpClient, that is, HttpClientHandler, but these two HttpClient was placed in the "pool" in the factory at a time when it will automatically create the judge is new or reuse. (The default life cycle 2min, you can modify the default lifecycle)
   // modify the default lifecycle 
services.AddHttpClient () .SetHandlerLifetime (TimeSpan.FromMinutes (5));

Four, HttpClientFactory use 

    A first way to use

  1. Registered in the Startup.cs
                // http request registration service
                services.AddHttpClient();

         2.Httphelper request using auxiliary class

Copy the code
/// <summary>
        /// injecting http requests
        /// </summary>
        private readonly IHttpClientFactory httpClientFactory;
        public HttpHelp(IHttpClientFactory _httpClientFactory)
        {
            httpClientFactory = _httpClientFactory;
        }

        // <summary>
        // Get the requested data
        // <para> final submission </ para> manner url parameters
        // </summary>
        // <param name = "parameters"> parameter dictionary, can be empty </ param>
        // <param name="requestUri">例如/api/Files/UploadFile</param>
        // <returns></returns>
        public async Task<string> Get(Dictionary<string, string> parameters, string requestUri, string token)
        {
            // Get request object from the factory
            var client = httpClientFactory.CreateClient();
            // add request headers
            if (!string.IsNullOrWhiteSpace(token))
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }
            client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            // stitching address
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(requestUri, '?', strParam);
            }
            client.BaseAddress = new Uri(requestUri);
            return client.GetStringAsync(requestUri).Result;
        }
Copy the code

             3. Then we pair of opposing classes will be able to use registered in Startup.cs.

      Second, use a named client

     1. Sign in Startup.cs, this registration can be multiple. To create a distinguished name

Copy the code
services.AddHttpClient("github", c =>
{
    c.BaseAddress = new Uri("https://xxxxxxx.com/");
    // Github API versioning
    c.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
    // Github requires a user-agent
    c.DefaultRequestHeaders.Add("Authorization", "asfasfasdsgdsfsdfsdafasfas");
});
Copy the code

           2. Use the same way and as long as the above

Copy the code
/// <summary>
        /// injecting http requests
        /// </summary>
        private readonly IHttpClientFactory httpClientFactory;
        public HttpHelp(IHttpClientFactory _httpClientFactory)
        {
            httpClientFactory = _httpClientFactory;
        }

        // <summary>
        // Get the requested data
        // <para> final submission </ para> manner url parameters
        // </summary>
        // <param name = "parameters"> parameter dictionary, can be empty </ param>
        // <param name="requestUri">例如/api/Files/UploadFile</param>
        // <returns></returns>
        public async Task<string> Get(Dictionary<string, string> parameters, string requestUri, string token)
        {
            // Get request object from the factory which declare themselves a client creates httpClient
            var client = httpClientFactory.CreateClient("github");
            // add request headers
            if (!string.IsNullOrWhiteSpace(token))
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }
            client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            // stitching address
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(requestUri, '?', strParam);
            }
            client.BaseAddress = new Uri(requestUri);
            return client.GetStringAsync(requestUri).Result;
        }
Copy the code

         Third, the type of client

           1. Create a class

Copy the code
public class HttpClienService
{
    public HttpClient Client { get; }
    public HttpClienService(HttpClient client)
    {
        client.BaseAddress = new Uri("https://xxxx.com/");
        // GitHub API versioning
        client.DefaultRequestHeaders.Add("Authorization",
            "xxxxxxxxxxxx");
        // GitHub requires a user-agent
        client.DefaultRequestHeaders.Add("Content-Type",
            "application/json; charset=utf-8");
        Customer = customer;
    } 

// The following method is to write your own, call }
Copy the code

             2. Sign in Startup.cs, this registration can be multiple.

services.AddHttpClient <classHttp> (); 
then // register, way dependency injection injection, use.

Guess you like

Origin www.cnblogs.com/zhuyuchao/p/12212750.html