WebApi series ~ Performance hazards of HttpClient: webapihttpclient
Back to directory
During the development process recently, all interfaces are developed. The A-station interface accesses the B-interface to request data. In this process, we use the HttpClient framework, of course, it is also Microsoft's own framework, and the performance is no problem at present, but if you directly use the official writing method, there will be a great performance risk in high concurrency, because it is officially using the using method, and for a large number of requests, this method will be too high for TCP establishment, even if you release it immediately, there will be a lot of time_out requests, all decided to make a static component using httpclient!
Details
Statistics
Call, reasonable writing
using (var http = new HttpClient()) { var json = JsonConvert.SerializeObject(new { target_index = projectName, timestamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"), Level = level.ToString(), Message = message }); json = json.Replace("target_index", "@target_index").Replace("timestamp", "@timestamp"); var httpContent = new StringContent(json, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = http.PostAsync(apiLoggerUri, httpContent).Result; }
It is optimized to form a TCP persistent link, so the request goes through a channel
private static readonly HttpClient _httpClient; private ApiLoggerOptions _config; static ApiLogger() { _httpClient = new HttpClient(); _httpClient.Timeout = new TimeSpan(0, 0, 10); _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive"); }
The keep-alive keyword can be understood as a long link, and the timeout value can also be set on it. For example, the timeout value of 10 seconds is too large, and many requests should be discarded in 10 seconds.
The request sending Code does not have using, that is, the httpclient will not be manually dispose, but is controlled by the system. Of course, when your program is restarted, this will be recycled.
var json = JsonConvert.SerializeObject(new { target_index = projectName, timestamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"), Level = level.ToString(), Message = message }); json = json.Replace("target_index", "@target_index").Replace("timestamp", "@timestamp"); var httpContent = new StringContent(json, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); _httpClient.PostAsync(apiLoggerUri, httpContent).Wait();
Through the above transformation, our system performance has been improved, and the number of TCP connections has also dropped.
Therefore, for long-link multiplexing technology, it is the most resource-saving compared to too many requests!
Back to directory