欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在ASP.NET Core中使用HttpClientFactory

 更新時(shí)間:2021年04月09日 09:28:35   作者:碼農(nóng)讀書  
這篇文章主要介紹了如何在ASP.NET Core中使用HttpClientFactory,幫助大家更好的理解和學(xué)習(xí)使用.net技術(shù),感興趣的朋友可以了解下

ASP.Net Core 是一個(gè)開源的,跨平臺(tái)的,輕量級(jí)模塊化框架,可用它來(lái)構(gòu)建高性能的Web程序,這篇文章我們將會(huì)討論如何在 ASP.Net Core 中使用 HttpClientFactory。

為什么要使用 HttpClientFactory

可以用 HttpClientFactory 來(lái)集中化管理 HttpClient,工廠提供了對(duì) HttpClient 的創(chuàng)建,配置和調(diào)度,值得一提的是:HttpClient 一直都是 Http 請(qǐng)求業(yè)務(wù)方面的一等公民。

HttpClient 雖好,但它有一些缺點(diǎn):

  • 創(chuàng)建太多的 HttpClient 是一種低效的行為,因?yàn)楫?dāng)一個(gè)新客戶端連接到遠(yuǎn)程 Server 時(shí),你的應(yīng)用程序還需要承擔(dān)著重連遠(yuǎn)程 Server 的開銷。
  • 如果每一個(gè) request 都創(chuàng)建一個(gè) HttpClient,當(dāng)應(yīng)用程序負(fù)載過(guò)大, Socket 必將耗盡,比如默認(rèn)情況下 HttpClient 會(huì)維持至少4分鐘的 Connection 連接。

所以推薦的做法是創(chuàng)建一個(gè)可供復(fù)用的共享式 HttpClient 實(shí)例,如果你要打破沙鍋問(wèn)到低的話,即使是創(chuàng)建共享式的 HttpClient 也會(huì)有很多問(wèn)題,比如它會(huì)無(wú)視 DNS 緩存生效,那怎么辦呢?可以用 .NET Core 2.1 引入的 HttpClientFactory 來(lái)解決此問(wèn)題。。。用它來(lái)統(tǒng)一化的高效管理 HttpClient。

使用 HttpClientFactory

HttpClientFactory 有兩種使用方式。

  • NamedClient
  • TypedClient

所謂的 NamedClient 就是注冊(cè)帶有標(biāo)記的 HttpClient 到 HttpClientFactory 工廠中,下面的代碼展示了一個(gè)名為 IDGCustomApi 的 HttpClient 的工廠注冊(cè)。

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient("IDGCustomApi", client =>
            {
                client.BaseAddress = new Uri("https://localhost:6045/");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "IDG");
            });

            services.AddControllers();
        }

所謂的 TypedClient 就是注冊(cè)一個(gè)你自定義的 HttpClient,我想你肯定有點(diǎn)懵逼了,沒(méi)關(guān)系,我現(xiàn)在就來(lái)自定義 HttpClient, 然后通過(guò) AddHttpClient() 注冊(cè)到容器中。

    public class CustomHttpClient
    {
        public HttpClient Client { get; }

        public CustomHttpClient(HttpClient client)
        {
            Client = client;
        }
    }

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient<CustomHttpClient>(client => client.BaseAddress = new Uri("https://localhost:6045/"));

            services.AddControllers();
        }
    }

注入 Controller

為了能夠在 Controller 中使用,可以將 IHttpClientFactory 通過(guò)構(gòu)造函數(shù)方式進(jìn)行注入,參考如下代碼:

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private IHttpClientFactory httpClientFactory;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }

        [HttpGet]
        public async Task<string> Get()
        {
            var httpClient = httpClientFactory.CreateClient("IDGCustomApi");

            string html = await httpClient.GetStringAsync("http://bing.com");

            return html;
        }
    }

從 IHttpClientFactory 的默認(rèn)實(shí)現(xiàn) DefaultHttpClientFactory 的源碼也可以看出,httpClient 所關(guān)聯(lián)的 HttpMessageHandler 和 Options 都被工廠跟蹤和管控。

    internal class DefaultHttpClientFactory : IHttpClientFactory, IHttpMessageHandlerFactory
    {
        public HttpClient CreateClient(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            HttpMessageHandler handler = CreateHandler(name);
            HttpClient httpClient = new HttpClient(handler, disposeHandler: false);
            HttpClientFactoryOptions httpClientFactoryOptions = _optionsMonitor.Get(name);
            for (int i = 0; i < httpClientFactoryOptions.HttpClientActions.Count; i++)
            {
                httpClientFactoryOptions.HttpClientActions[i](httpClient);
            }
            return httpClient;
        }

        public HttpMessageHandler CreateHandler(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            ActiveHandlerTrackingEntry value = _activeHandlers.GetOrAdd(name, _entryFactory).Value;
            StartHandlerEntryTimer(value);
            return value.Handler;
        }
    }

譯文鏈接:https://www.infoworld.com/article/3276007/how-to-work-with-httpclientfactory-in-aspnet-core.html

以上就是如何在ASP.NET Core中使用HttpClientFactory的詳細(xì)內(nèi)容,更多關(guān)于ASP.NET Core使用HttpClientFactory的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論