之所以做这个实验是因为最近利用微软的QnAMaker实现一个机器人的简单对话,但是使用过程中,偶尔会有回复特别慢的情况出现,检查代码发现是httpclient请求QnAMaker时耗时太久。
以下是我的代码。
public static class QnAHttpClient { private static string host = "https://rektecqna.azurewebsites.net/qnamaker"; private static string endpoint_key = "xxxxxxxxxxxxxxxxxxx"; private static string method = "/knowledgebases/xxxxxxxxxx/generateAnswer"; static QnAHttpClient() { _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri(host+ method); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.Timeout = new TimeSpan(0, 1, 0); _httpClient.DefaultRequestHeaders.Add("Authorization", "EndpointKey " + endpoint_key); } private static HttpClient _httpClient; private static HttpClient Client { get { return _httpClient; } } public static async Task GetQnAMakerAnswerDic(string question) { try { using (var request = new HttpRequestMessage()) { var postBody = $"{{\"question\": \"{question}\",\"top\": 5}}"; request.Method = HttpMethod.Post; request.Content = new StringContent(postBody, Encoding.UTF8, "application/json"); request.Headers.Add("Authorization", "EndpointKey " + endpoint_key); var response = await Client.SendAsync(request); var retString = await response.Content.ReadAsStringAsync(); ConsoleHelper.WriteLine(retString); } } catch (Exception ex) { ConsoleHelper.WriteLine(ex.ToString()); } ConsoleHelper.WriteLine("QnA_end"); } public static async Task GetQnAMakerAnswerDic2(string question) { //ConsoleHelper.WriteLine("QnA"); try { { var postBody = $"{{\"question\": \"{question}\",\"top\": 5}}"; using (var response = await Client.PostAsync("" , new StringContent(postBody, Encoding.UTF8, "application/json"))) { var retString = await response.Content.ReadAsStringAsync(); } } } catch (Exception ex) { ConsoleHelper.WriteLine(ex.ToString()); } ConsoleHelper.WriteLine("QnA_end"); } }100次实验耗时对比:
1000次结果对比:
对比出,直接用httpclient的postasync方法的最大值要小一些,单看平均值差距并不是太大,但是大家用的时候还是要用postasync吧,在网上看到别人说的,应该是有一定道理的
但是最大耗时还是很久。。。。。。。。。
我的解决方法L:
1.设置timeout时间2秒
2.使用之前调用一次httpclient.postasync,之后的请求就还好