最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

DotNetCore深入了解之HttpClientFactory類詳解

 更新時間:2019年03月03日 14:39:46   作者:李志章  
這篇文章主要給大家介紹了關(guān)于DotNetCore深入了解之HttpClientFactory類的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

當(dāng)需要向某特定URL地址發(fā)送HTTP請求并得到相應(yīng)響應(yīng)時,通常會用到HttpClient類。該類包含了眾多有用的方法,可以滿足絕大多數(shù)的需求。但是如果對其使用不當(dāng)時,可能會出現(xiàn)意想不到的事情。

using(var client = new HttpClient())

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

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

所以比較好的解決方法是延長HttpClient對象的使用壽命,比如對其建一個靜態(tài)的對象:

private static HttpClient Client = new HttpClient();

但從程序員的角度來看,這樣的代碼或許不夠優(yōu)雅。

所以在.NET Core 2.1中引入了新的HttpClientFactory類。

它的用法很簡單,首先是對其進(jìn)行IoC的注冊:

 public void ConfigureServices(IServiceCollection services)
 {
  services.AddHttpClient();
  services.AddMvc();
 }

然后通過IHttpClientFactory創(chuàng)建一個HttpClient對象,之后的操作如舊,但不需要擔(dān)心其內(nèi)部資源的釋放:

public class LzzDemoController : Controller
{
 IHttpClientFactory _httpClientFactory;

 public LzzDemoController(IHttpClientFactory httpClientFactory)
 {
  _httpClientFactory = httpClientFactory;
 }

 public IActionResult Index()
 {
  var client = _httpClientFactory.CreateClient();
  var result = client.GetStringAsync("http://myurl/");
  return View();
 }
}

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;
}

它的內(nèi)部為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為鍵值從一字典中取出,又因?yàn)镈efaultHttpClientFactory類是通過TryAddSingleton方法注冊的,也就意味著其為單例,那么這個內(nèi)部字典便是唯一的,每個鍵值對應(yīng)的ActiveHandlerTrackingEntry對象也是唯一,該對象內(nèi)部中包含著handler。

下一句代碼StartHandlerEntryTimer(entry); 開啟了ActiveHandlerTrackingEntry對象的過期計時處理。默認(rèn)過期時間是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對象被放入專用的隊(duì)列。

最后開始清理工作,定時器的時間間隔設(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類的擴(kuò)展方法。

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

 return factory.CreateClient(Options.DefaultName);
}

Options.DefaultName的值為string.Empty。

DefaultHttpClientFactory缺少無參數(shù)的構(gòu)造方法,唯一的構(gòu)造方法需要傳入多個參數(shù),這也意味著構(gòu)建它時需要依賴其它一些類,所以目前只適用于在ASP.NET程序中使用,還無法應(yīng)用到諸如控制臺一類的程序,希望之后官方能夠?qū)ζ淅^續(xù)增強(qiáng),使得應(yīng)用范圍變得更廣。

 public DefaultHttpClientFactory(
  IServiceProvider services,
  ILoggerFactory loggerFactory,
  IOptionsMonitor<HttpClientFactoryOptions> optionsMonitor,
  IEnumerable<IHttpMessageHandlerBuilderFilter> filters)

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

  • ASP.NET預(yù)定義模板介紹

    ASP.NET預(yù)定義模板介紹

    在調(diào)用這些方法的時候,如果我們指定了一個具體的通過分部View定義的模板,或者對應(yīng)的ModelMetadata的TemplateHint屬性具有一個模板名稱,會自動采用該模板來生成最終的HTML,需要了解這方面內(nèi)容的朋友可以參考一下
    2015-10-10
  • asp.net core集成kindeditor實(shí)現(xiàn)圖片上傳功能

    asp.net core集成kindeditor實(shí)現(xiàn)圖片上傳功能

    這篇文章主要為大家詳細(xì)介紹了asp.net core集成kindeditor實(shí)現(xiàn)圖片上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • asp.net實(shí)現(xiàn)的群發(fā)郵件功能詳解

    asp.net實(shí)現(xiàn)的群發(fā)郵件功能詳解

    這篇文章主要介紹了asp.net實(shí)現(xiàn)的群發(fā)郵件功能,結(jié)合具體實(shí)例形式分析了asp.net基于SMTP服務(wù)群發(fā)QQ郵件的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2017-05-05
  • Asp.net清空控件值的方法(可自定義控件類型)

    Asp.net清空控件值的方法(可自定義控件類型)

    頁面內(nèi)有許多控件,在清理的過程中很費(fèi)時間,于是寫了這么一個方法,可以自定義清空控件的類型,感興趣的朋友可以參考下哈
    2013-04-04
  • 淺析ASP.NET生成隨機(jī)密碼函數(shù)

    淺析ASP.NET生成隨機(jī)密碼函數(shù)

    在開發(fā)需要用戶注冊后才能使用提供的各項(xiàng)功能的應(yīng)用程序時,在新用戶提交注冊信息后,較常見的做法是由程序生成隨機(jī)密碼,然后發(fā)送密碼到用戶注冊時填寫的電子信箱,用戶再用收到的密碼來激活其帳戶。
    2009-11-11
  • asp.net中javascript與后臺c#交互

    asp.net中javascript與后臺c#交互

    這篇文章主要介紹了asp.net中javascript與后臺c#交互,需要的朋友可以參考下
    2015-10-10
  • ASP.NET驗(yàn)證碼(3種)

    ASP.NET驗(yàn)證碼(3種)

    這篇文章主要對ASP.NET實(shí)現(xiàn)三種驗(yàn)證碼的簡單實(shí)例進(jìn)行了介紹,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2015-08-08
  • ASP.NET中JQuery+AJAX調(diào)用后臺

    ASP.NET中JQuery+AJAX調(diào)用后臺

    這篇文章主要介紹了ASP.NET中JQuery+AJAX調(diào)用后臺的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • 如何在.net6webapi中使用自動依賴注入

    如何在.net6webapi中使用自動依賴注入

    IOC/DI是一種設(shè)計模式,用于解耦組件之間的依賴關(guān)系,在傳統(tǒng)的編程模式中,組件之間的依賴關(guān)系是硬編碼在代碼中的,這樣會導(dǎo)致代碼的耦合度很高,難以維護(hù)和發(fā)展,這篇文章主要介紹了如何在.net6webapi中實(shí)現(xiàn)自動依賴注入,需要的朋友可以參考下
    2023-06-06
  • Asp.Net使用服務(wù)器控件Image/ImageButton顯示本地圖片的方法

    Asp.Net使用服務(wù)器控件Image/ImageButton顯示本地圖片的方法

    Image/ImageButton服務(wù)器控件顯示本地的圖片,實(shí)現(xiàn)思路是數(shù)據(jù)庫中存放了圖片的相對地址,讀取數(shù)據(jù)庫中的地址,用控件加載顯示圖片。具體實(shí)現(xiàn)步驟大家參考下本文
    2017-08-08

最新評論

海宁市| 锡林郭勒盟| 宁阳县| 汾阳市| 临朐县| 凤冈县| 竹北市| 双辽市| 吉水县| 奉新县| 鹤壁市| 鄄城县| 遂平县| 江西省| 醴陵市| 麻江县| 宁南县| 九龙坡区| 吴川市| 婺源县| 铁岭市| 乌拉特前旗| 镇赉县| 拜城县| 黎平县| 临武县| 凤台县| 枣强县| 仪陇县| 河南省| 塔城市| 紫阳县| 台南县| 渑池县| 静安区| 黄陵县| 明光市| 玉门市| 青岛市| 湄潭县| 密山市|