當須要向某特定URL地址發送HTTP請求並獲得相應響應時,一般會用到HttpClient類。該類包含了衆多有用的方法,能夠知足絕大多數的需求。可是若是對其使用不當時,可能會出現意想不到的事情。程序員
using(var client = new HttpClient())
對象所佔用資源應該確保及時被釋放掉,可是,對於網絡鏈接而言,這是錯誤的。網絡
緣由有二,網絡鏈接是須要耗費必定時間的,頻繁開啓與關閉鏈接,性能會受影響;再者,開啓網絡鏈接時會佔用底層socket資源,但在HttpClient調用其自己的Dispose方法時,並不能馬上釋放該資源,這意味着你的程序可能會由於耗盡鏈接資源而產生預期以外的異常。app
因此比較好的解決方法是延長HttpClient對象的使用壽命,好比對其建一個靜態的對象:socket
private static HttpClient Client = new HttpClient();
但從程序員的角度來看,這樣的代碼或許不夠優雅。ide
因此在.NET Core 2.1中引入了新的HttpClientFactory類。性能
它的用法很簡單,首先是對其進行IoC的註冊:ui
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddHttpClient(); 4 services.AddMvc(); 5 }
而後經過IHttpClientFactory建立一個HttpClient對象,以後的操做如舊,但不須要擔憂其內部資源的釋放:this
1 public class LzzDemoController : Controller 2 { 3 IHttpClientFactory _httpClientFactory; 4 5 public LzzDemoController(IHttpClientFactory httpClientFactory) 6 { 7 _httpClientFactory = httpClientFactory; 8 } 9 10 public IActionResult Index() 11 { 12 var client = _httpClientFactory.CreateClient(); 13 var result = client.GetStringAsync("http://myurl/"); 14 return View(); 15 } 16 }
AddHttpClient的源碼:url
1 public static IServiceCollection AddHttpClient(this IServiceCollection services) 2 { 3 if (services == null) 4 { 5 throw new ArgumentNullException(nameof(services)); 6 } 7 8 services.AddLogging(); 9 services.AddOptions(); 10 11 // 12 // Core abstractions 13 // 14 services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>(); 15 services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>(); 16 17 // 18 // Typed Clients 19 // 20 services.TryAdd(ServiceDescriptor.Singleton(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>))); 21 22 // 23 // Misc infrastructure 24 // 25 services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>()); 26 27 return services; 28 }
它的內部爲IHttpClientFactory接口綁定了DefaultHttpClientFactory類。idea
再看IHttpClientFactory接口中關鍵的CreateClient方法:
1 public HttpClient CreateClient(string name) 2 { 3 if (name == null) 4 { 5 throw new ArgumentNullException(nameof(name)); 6 } 7 8 var entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value; 9 var client = new HttpClient(entry.Handler, disposeHandler: false); 10 11 StartHandlerEntryTimer(entry); 12 13 var options = _optionsMonitor.Get(name); 14 for (var i = 0; i < options.HttpClientActions.Count; i++) 15 { 16 options.HttpClientActions[i](client); 17 } 18 19 return client; 20 }
HttpClient的建立再也不是簡單的new HttpClient(),而是傳入了兩個參數:HttpMessageHandler handler與bool disposeHandler。disposeHandler參數爲false值時表示要重用內部的handler對象。handler參數則從上一句的代碼能夠看出是以name爲鍵值從一字典中取出,又由於DefaultHttpClientFactory類是經過TryAddSingleton方法註冊的,也就意味着其爲單例,那麼這個內部字典即是惟一的,每一個鍵值對應的ActiveHandlerTrackingEntry對象也是惟一,該對象內部中包含着handler。
下一句代碼StartHandlerEntryTimer(entry);
開啓了ActiveHandlerTrackingEntry對象的過時計時處理。默認過時時間是2分鐘。
1 internal void ExpiryTimer_Tick(object state) 2 { 3 var active = (ActiveHandlerTrackingEntry)state; 4 5 // The timer callback should be the only one removing from the active collection. If we can't find 6 // our entry in the collection, then this is a bug. 7 var removed = _activeHandlers.TryRemove(active.Name, out var found); 8 Debug.Assert(removed, "Entry not found. We should always be able to remove the entry"); 9 Debug.Assert(object.ReferenceEquals(active, found.Value), "Different entry found. The entry should not have been replaced"); 10 11 // At this point the handler is no longer 'active' and will not be handed out to any new clients. 12 // However we haven't dropped our strong reference to the handler, so we can't yet determine if 13 // there are still any other outstanding references (we know there is at least one). 14 // 15 // We use a different state object to track expired handlers. This allows any other thread that acquired 16 // the 'active' entry to use it without safety problems. 17 var expired = new ExpiredHandlerTrackingEntry(active); 18 _expiredHandlers.Enqueue(expired); 19 20 Log.HandlerExpired(_logger, active.Name, active.Lifetime); 21 22 StartCleanupTimer(); 23 }
先是將ActiveHandlerTrackingEntry對象傳入新的ExpiredHandlerTrackingEntry對象。
1 public ExpiredHandlerTrackingEntry(ActiveHandlerTrackingEntry other) 2 { 3 Name = other.Name; 4 5 _livenessTracker = new WeakReference(other.Handler); 6 InnerHandler = other.Handler.InnerHandler; 7 }
在其構造方法內部,handler對象經過弱引用方式關聯着,不會影響其被GC釋放。
而後新建的ExpiredHandlerTrackingEntry對象被放入專用的隊列。
最後開始清理工做,定時器的時間間隔設定爲每10秒一次。
1 internal void CleanupTimer_Tick(object state) 2 { 3 // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup. 4 // 5 // With the scheme we're using it's possible we could end up with some redundant cleanup operations. 6 // This is expected and fine. 7 // 8 // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it 9 // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out 10 // whether we need to start the timer. 11 StopCleanupTimer(); 12 13 try 14 { 15 if (!Monitor.TryEnter(_cleanupActiveLock)) 16 { 17 // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes 18 // a long time for some reason. Since we're running user code inside Dispose, it's definitely 19 // possible. 20 // 21 // If we end up in that position, just make sure the timer gets started again. It should be cheap 22 // to run a 'no-op' cleanup. 23 StartCleanupTimer(); 24 return; 25 } 26 27 var initialCount = _expiredHandlers.Count; 28 Log.CleanupCycleStart(_logger, initialCount); 29 30 var stopwatch = ValueStopwatch.StartNew(); 31 32 var disposedCount = 0; 33 for (var i = 0; i < initialCount; i++) 34 { 35 // Since we're the only one removing from _expired, TryDequeue must always succeed. 36 _expiredHandlers.TryDequeue(out var entry); 37 Debug.Assert(entry != null, "Entry was null, we should always get an entry back from TryDequeue"); 38 39 if (entry.CanDispose) 40 { 41 try 42 { 43 entry.InnerHandler.Dispose(); 44 disposedCount++; 45 } 46 catch (Exception ex) 47 { 48 Log.CleanupItemFailed(_logger, entry.Name, ex); 49 } 50 } 51 else 52 { 53 // If the entry is still live, put it back in the queue so we can process it 54 // during the next cleanup cycle. 55 _expiredHandlers.Enqueue(entry); 56 } 57 } 58 59 Log.CleanupCycleEnd(_logger, stopwatch.GetElapsedTime(), disposedCount, _expiredHandlers.Count); 60 } 61 finally 62 { 63 Monitor.Exit(_cleanupActiveLock); 64 } 65 66 // We didn't totally empty the cleanup queue, try again later. 67 if (_expiredHandlers.Count > 0) 68 { 69 StartCleanupTimer(); 70 } 71 }
上述方法核心是判斷是否handler對象已經被GC,若是是的話,則釋放其內部資源,即網絡鏈接。
回到最初建立HttpClient的代碼,會發現並無傳入任何name參數值。這是得益於HttpClientFactoryExtensions類的擴展方法。
1 public static HttpClient CreateClient(this IHttpClientFactory factory) 2 { 3 if (factory == null) 4 { 5 throw new ArgumentNullException(nameof(factory)); 6 } 7 8 return factory.CreateClient(Options.DefaultName); 9 }
Options.DefaultName的值爲string.Empty。
DefaultHttpClientFactory缺乏無參數的構造方法,惟一的構造方法須要傳入多個參數,這也意味着構建它時須要依賴其它一些類,因此目前只適用於在ASP.NET程序中使用,還沒法應用到諸如控制檯一類的程序,但願以後官方可以對其繼續加強,使得應用範圍變得更廣。
1 public DefaultHttpClientFactory( 2 IServiceProvider services, 3 ILoggerFactory loggerFactory, 4 IOptionsMonitor<HttpClientFactoryOptions> optionsMonitor, 5 IEnumerable<IHttpMessageHandlerBuilderFilter> filters)