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

.NET Core中的HttpClientFactory類用法詳解

 更新時間:2022年03月26日 14:59:59   作者:.NET開發(fā)菜鳥  
本文詳細講解了.NET Core中的HttpClientFactory類的用法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、HttpClient使用

在C#中,如果我們需要向某特定的URL地址發(fā)送Http請求的時候,通常會用到HttpClient類。會將HttpClient包裹在using內(nèi)部進行聲明和初始化,如下面的代碼:

using (var httpClient = new HttpClient())
{
    // 邏輯處理代碼
}

HttpClient類包含了許多有用的方法,使用上面的代碼,可以滿足絕大多數(shù)的需求,但是如果對其使用不當(dāng)時,可能會出現(xiàn)意想不到的事情。

上面代碼的技術(shù)范點:當(dāng)你使用繼承了IDisposable接口的對象時,建議在using代碼塊中聲明和初始化,當(dāng)using代碼段執(zhí)行完成后,會自動釋放該對象而不需要手動進行顯示Dispose操作。

對象所占用資源應(yīng)該確保及時被釋放掉,但是,對于網(wǎng)絡(luò)連接而言,這是錯誤的。具體原因有下面兩點:

  • 網(wǎng)絡(luò)連接是需要耗費一定時間的,頻繁開啟與關(guān)閉連接,性能會受到影響。
  • 開啟網(wǎng)絡(luò)連接時會占用低層socket資源,但在HttpClient調(diào)用其本身的Dispose方法時,并不能立即釋放該資源,這意味著你的程序可能會因為耗盡連接資源而產(chǎn)生預(yù)期之外的異常。

看下面一段代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HttpClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //using (var httpClient = new HttpClient())
            //{
            //    // 邏輯處理代碼
            //}

            HttpAsync();
            Console.WriteLine("Hello World!");
            Console.Read();

        }

        public static async void HttpAsync()
        {
            for (int i = 0; i < 10; i++)
            {
                using (var client = new HttpClient())
                {
                    var result = await client.GetAsync("http://www.baidu.com");
                    Console.WriteLine($"{i}:{result.StatusCode}");
                }
            }
        }
    }
}

 運行項目輸出結(jié)果后,通過netstate查看下TCP連接情況,會發(fā)現(xiàn)連接依然存在,狀態(tài)為“TIME_WAIT”(繼續(xù)等待看是否還有延遲的包會傳輸過來)。

這里就會出現(xiàn)一個坑:在高并發(fā)的情況下,連接來不及釋放,socket連接被耗盡,耗盡之后就會出現(xiàn)錯誤。就是會出現(xiàn)“各種套接字問題”。

那么如何解決這個問題呢?比較好的解決方法是延長HttpClient對象的使用壽命,實現(xiàn)HttpClient對象的復(fù)用,比如對其建一個靜態(tài)的對象:

private static HttpClient Client = new HttpClient();

我們使用這種方式優(yōu)化上面的代碼 

using System;
using System.Net.Http;

namespace HttpClientDemo
{
    class Program
    {
        private static readonly HttpClient _client = new HttpClient();
        static void Main(string[] args)
        {
            HttpAsync();
            Console.WriteLine("Hello World");
            Console.ReadKey();
        }

        public static async void HttpAsync()
        {
            for (int i = 0; i < 10; i++)
            {
                var result = await _client.GetAsync("http://www.baidu.com");
                Console.WriteLine($"{i}:{result.StatusCode}");
            }
        }

    }
}

這樣調(diào)整HttpClient的引用后,雖然可以解決一些問題,但是仍然存在一些問題:

  • 因為是復(fù)用的HttpClient,那么一些公共的設(shè)置就沒辦法靈活的調(diào)整,如請求頭的自定義。
  • 因為HttpClient請求每個url時,會緩存url對應(yīng)的主機ip,從而會導(dǎo)致DNS更新失效。

為了解決這些問題,在.NET Core 2.1中引入了新的HttpClientFactory類。

二、HttpClientFactory使用

微軟在.NET Core 2.1中新引入了HttpClientFactory類,具有如下的優(yōu)勢:

  • HttpClientFactory很高效,可以最大程度上節(jié)省系統(tǒng)的sock而。
  • Factory,顧名思義HttpClientfactory就是HttpClient的工廠,內(nèi)部已經(jīng)幫我們處理好了對HttpClient的管理,不需要我們?nèi)斯みM行對象釋放,同時,支持自定義請求頭、支持DNS更新等。

我們用一個ASP.NET Core的程序作為示例,它的用法非常簡單,首先是對其進行IOC注冊:

public void ConfigureServices(IServiceCollection services)
{
    // 注入HttpClient
    services.AddHttpClient("client_1", config =>  //這里指定的name=client_1,可以方便我們后期服用該實例
    {
        config.BaseAddress = new Uri("http://www.baidu.com");
        config.DefaultRequestHeaders.Add("header_1", "header_1");
    });
    services.AddHttpClient("client_2", config =>
    {
        config.BaseAddress = new Uri("https://www.qq.com/");
        config.DefaultRequestHeaders.Add("header_2", "header_2");
    });
    services.AddHttpClient();
    services.AddControllers();
}

然后在控制器里面通過IHttpClientFactory創(chuàng)建一個HttpClient對象,之后的操作跟以前一樣,但不需要擔(dān)心其內(nèi)部資源的釋放:

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace HttpClientFactoryDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 通過構(gòu)造函數(shù)實現(xiàn)注入
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public DemoController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<string> Get()
        {
            var client = _httpClientFactory.CreateClient("client_1"); //復(fù)用在Startup中定義的client_1的httpclient
            var result = await client.GetStringAsync("/page1.html");

            var client2 = _httpClientFactory.CreateClient(); //新建一個HttpClient
            var result2 = await client.GetAsync("http://www.baidu.com");



            return result2.StatusCode.ToString();
        }
    }
}

程序運行結(jié)果:

 

AddHttpClient的源碼:

public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddLogging();
    services.AddOptions();

    //
    // Core abstractions
    //
    services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
    services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();

    //
    // Typed Clients
    //
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>)));

    //
    // Misc infrastructure
    //
    services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>());

    return services;
}

看下面這句代碼:

services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();

這里添加依賴注入的時候為IHttpClientFactory接口綁定了DefaultHttpClientFactory類。

我們在來看IHttpClientFactory接口中關(guān)鍵的CreateClient方法:

public HttpClient CreateClient(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    var entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value;
    var client = new HttpClient(entry.Handler, disposeHandler: false);

    StartHandlerEntryTimer(entry);

    var options = _optionsMonitor.Get(name);
    for (var i = 0; i < options.HttpClientActions.Count; i++)
    {
        options.HttpClientActions[i](client);
    }

    return client;
}

從代碼中我們可以看出:HttpClient的創(chuàng)建不在是簡單的new HttpClient(),而是傳入了兩個參數(shù):HttpMessageHandler handler與bool disposeHandler。

disposeHandler參數(shù)為false時表示要重用內(nèi)部的handler對象。handler參數(shù)則從上一句的代碼中可以看出是以name為鍵值從一字典中取出,又因為DefaultHttpClientFactory類是通過TryAddSingleton方法注冊的,也就意味著其為單例,那么這個內(nèi)部字典便是唯一的,每個鍵值對應(yīng)的ActiveHandlerTrackingEntry對象也是唯一,該對象內(nèi)部中包含著handler。

下一句代碼StartHandlerEntryTimer(entry); 開啟了ActiveHandlerTrackingEntry對象的過期計時處理。默認過期時間是2分鐘。

internal void ExpiryTimer_Tick(object state)
{
    var active = (ActiveHandlerTrackingEntry)state;

    // The timer callback should be the only one removing from the active collection. If we can't find
    // our entry in the collection, then this is a bug.
    var removed = _activeHandlers.TryRemove(active.Name, out var found);
    Debug.Assert(removed, "Entry not found. We should always be able to remove the entry");
    Debug.Assert(object.ReferenceEquals(active, found.Value), "Different entry found. The entry should not have been replaced");

    // At this point the handler is no longer 'active' and will not be handed out to any new clients.
    // However we haven't dropped our strong reference to the handler, so we can't yet determine if
    // there are still any other outstanding references (we know there is at least one).
    //
    // We use a different state object to track expired handlers. This allows any other thread that acquired
    // the 'active' entry to use it without safety problems.
    var expired = new ExpiredHandlerTrackingEntry(active);
    _expiredHandlers.Enqueue(expired);

    Log.HandlerExpired(_logger, active.Name, active.Lifetime);

    StartCleanupTimer();
}

先是將ActiveHandlerTrackingEntry對象傳入新的ExpiredHandlerTrackingEntry對象。

public ExpiredHandlerTrackingEntry(ActiveHandlerTrackingEntry other)
{
    Name = other.Name;

    _livenessTracker = new WeakReference(other.Handler);
    InnerHandler = other.Handler.InnerHandler;
}

在其構(gòu)造方法內(nèi)部,handler對象通過弱引用方式關(guān)聯(lián)著,不會影響其被GC釋放。

然后新建的ExpiredHandlerTrackingEntry對象被放入專用的隊列。

最后開始清理工作,定時器的時間間隔設(shè)定為每10秒一次。

internal void CleanupTimer_Tick(object state)
{
    // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup.
    //
    // With the scheme we're using it's possible we could end up with some redundant cleanup operations.
    // This is expected and fine.
    //
    // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it
    // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out
    // whether we need to start the timer.
    StopCleanupTimer();

    try
    {
        if (!Monitor.TryEnter(_cleanupActiveLock))
        {
            // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes
            // a long time for some reason. Since we're running user code inside Dispose, it's definitely
            // possible.
            //
            // If we end up in that position, just make sure the timer gets started again. It should be cheap
            // to run a 'no-op' cleanup.
            StartCleanupTimer();
            return;
        }

        var initialCount = _expiredHandlers.Count;
        Log.CleanupCycleStart(_logger, initialCount);

        var stopwatch = ValueStopwatch.StartNew();

        var disposedCount = 0;
        for (var i = 0; i < initialCount; i++)
        {
            // Since we're the only one removing from _expired, TryDequeue must always succeed.
            _expiredHandlers.TryDequeue(out var entry);
            Debug.Assert(entry != null, "Entry was null, we should always get an entry back from TryDequeue");

            if (entry.CanDispose)
            {
                try
                {
                    entry.InnerHandler.Dispose();
                    disposedCount++;
                }
                catch (Exception ex)
                {
                    Log.CleanupItemFailed(_logger, entry.Name, ex);
                }
            }
            else
            {
                // If the entry is still live, put it back in the queue so we can process it
                // during the next cleanup cycle.
                _expiredHandlers.Enqueue(entry);
            }
        }

        Log.CleanupCycleEnd(_logger, stopwatch.GetElapsedTime(), disposedCount, _expiredHandlers.Count);
    }
    finally
    {
        Monitor.Exit(_cleanupActiveLock);
    }

    // We didn't totally empty the cleanup queue, try again later.
    if (_expiredHandlers.Count > 0)
    {
        StartCleanupTimer();
    }
}

上述方法核心是判斷是否handler對象已經(jīng)被GC,如果是的話,則釋放其內(nèi)部資源,即網(wǎng)絡(luò)連接。

回到最初創(chuàng)建HttpClient的代碼,會發(fā)現(xiàn)并沒有傳入任何name參數(shù)值。這是得益于HttpClientFactoryExtensions類的擴展方法。

public static HttpClient CreateClient(this IHttpClientFactory factory)
{
    if (factory == null)
    {
        throw new ArgumentNullException(nameof(factory));
    }

    return factory.CreateClient(Options.DefaultName);
}

Options.DefaultName的值為string.Empty。

到此這篇關(guān)于.NET Core中的HttpClientFactory類用法的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • .net core下配置訪問數(shù)據(jù)庫操作

    .net core下配置訪問數(shù)據(jù)庫操作

    本篇文章給大家詳細分享了在.net core下配置訪問數(shù)據(jù)庫的相關(guān)操作過程以及代碼實現(xiàn)過程,有興趣的朋友參考下。
    2018-03-03
  • .net core靜態(tài)中間件的使用

    .net core靜態(tài)中間件的使用

    本文主要整理了靜態(tài)中間件的使用,學(xué)習(xí).net core的朋友可以參考下本文
    2021-06-06
  • SQL Server 2008 R2:error 26 開啟遠程連接詳解

    SQL Server 2008 R2:error 26 開啟遠程連接詳解

    本篇文章小編為大家介紹,SQL Server 2008 R2:error 26 開啟遠程連接詳解。需要的朋友參考下
    2013-04-04
  • .NET?MAUI項目中創(chuàng)建超鏈接

    .NET?MAUI項目中創(chuàng)建超鏈接

    這篇文章介紹了.NET?MAUI項目中創(chuàng)建超鏈接的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • ASP.NET的廣告控件AdRotator用法分析

    ASP.NET的廣告控件AdRotator用法分析

    這篇文章主要介紹了ASP.NET的廣告控件AdRotator用法,較為詳細的分析了廣告控件AdRotator的功能、使用方法與相關(guān)注意事項,需要的朋友可以參考下
    2016-05-05
  • asp.net MVC使用PagedList.MVC實現(xiàn)分頁效果

    asp.net MVC使用PagedList.MVC實現(xiàn)分頁效果

    這篇文章主要為大家詳細介紹了asp.net MVC使用PagedList.MVC實現(xiàn)分頁效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • C#中使用SQLite數(shù)據(jù)庫的方法介紹

    C#中使用SQLite數(shù)據(jù)庫的方法介紹

    SQLite是一個開源的輕量級的桌面型數(shù)據(jù)庫,它將幾乎所有數(shù)據(jù)庫要素(包括定義、表、索引和數(shù)據(jù)本身)都保存在一個單一的文件中。SQLite用C編寫實現(xiàn),它在內(nèi)存消耗、文件體積、操作性能、簡單性方面都有不錯的表現(xiàn)
    2012-01-01
  • .NET8 依賴注入

    .NET8 依賴注入

    依賴注入是一種設(shè)計模式,用于解耦組件(服務(wù))之間的依賴關(guān)系,它通過將依賴關(guān)系的創(chuàng)建和管理交給外部容器來實現(xiàn),而不是在組件(服務(wù))內(nèi)部直接創(chuàng)建依賴對象,本文介紹.NET8 依賴注入的相關(guān)知識,感興趣的朋友一起看看吧
    2023-12-12
  • XML文件修改節(jié)點屬性值(多種方法)

    XML文件修改節(jié)點屬性值(多種方法)

    有關(guān)XML文件的節(jié)點屬性值修改在使用過程中經(jīng)常會遇到過,感興趣的朋友可以參考下本文,希望對你有所幫助
    2013-04-04
  • Asp.net 彈出對話框基類(輸出alet警告框)

    Asp.net 彈出對話框基類(輸出alet警告框)

    asp.net輸出alert警告框
    2008-11-11

最新評論