HttpClientFactory超时设置问题
作者:互联网
Startup.cs 配置
services.AddHttpClient("StockClient",client => { client.Timeout = TimeSpan.FromSeconds(3); client.BaseAddress = new Uri(Configuration["BaseAddress"]); client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded"); })
client.Timeout = TimeSpan.FromSeconds(3); httpclient的超时时间设置为3s
请求接口代码
_httpClient = HttpClientFactory.CreateClient("StockClient");
/// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task<QueryStockOutput> CheckArea(QueryStockInput input) { Stopwatch stopwatch = new Stopwatch(); HttpResponseMessage response = null; string readAsStringAsync; try { stopwatch.Start(); response = await _httpClient.PostAsync("https://localhost:5001/Home/Test", null); readAsStringAsync =await response.Content.ReadAsStringAsync(); } catch (Exception e) { stopwatch.Stop();
Logger.Info("LucyTestError"+ ":" + stopwatch.ElapsedMilliseconds);
throw e;
} System.Console.WriteLine(readAsStringAsync + ":" + stopwatch.ElapsedMilliseconds); return null; }
/Home/Test 代码
/// <summary> /// 被请求端 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> Test() { Thread.Sleep(3000); //必定超过3s return await Task.FromResult(Json("ok")); }
测试结果
基本上都是3s左右
但是加了一句 new List<KeyValuePair<string, string>>
var content = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("token", "惹我热无"), new KeyValuePair<string, string>("id", "范德萨范德萨") }; response = await _httpClient.PostAsync("https://localhost:5001/Home/Test", new FormUrlEncodedContent(content)); readAsStringAsync =await response.Content.ReadAsStringAsync();
耗时就比较夸张。。。。
why
标签:HttpClientFactory,await,Test,client,设置,stopwatch,new,超时,response 来源: https://www.cnblogs.com/xialele/p/13903214.html