C# .NET HttpClient在空闲约100秒后获取请求非常慢
第一个请求或怠速大约100秒后的请求非常慢,需要15-30秒。任何没有空转的请求都只需要不到一秒钟的时间。我同意第一个请求需要时间,只是不是因为很小的空闲时间导致了速度减慢 减速不是客户端独有的,如果我在一个客户端上不断发出请求,那么在另一个客户端上它会保持快速。只有当所有设备都闲置100秒时,它才会减速 以下是我尝试过的一些更改:C# .NET HttpClient在空闲约100秒后获取请求非常慢,c#,.net,amazon-web-services,amazon-s3,dotnet-httpclient,C#,.net,Amazon Web Services,Amazon S3,Dotnet Httpclient,第一个请求或怠速大约100秒后的请求非常慢,需要15-30秒。任何没有空转的请求都只需要不到一秒钟的时间。我同意第一个请求需要时间,只是不是因为很小的空闲时间导致了速度减慢 减速不是客户端独有的,如果我在一个客户端上不断发出请求,那么在另一个客户端上它会保持快速。只有当所有设备都闲置100秒时,它才会减速 以下是我尝试过的一些更改: 将HttpClient设置为单例,而不使用using()块处理它 将ServicePointManager.MaxServicePointIdleTime设置为更
- 将HttpClient设置为单例,而不使用using()块处理它
- 将ServicePointManager.MaxServicePointIdleTime设置为更高的值,因为默认值为100秒。由于时间段与我的时间段相同,我认为这是问题所在,但没有解决它
- 设置更高的ServicePointManager.DefaultConnectionLimit
- 通过web.config设置的默认代理设置
- 使用wait而不是httpClient.SendAsync(请求).Result
//获取httpclient单例或创建
var httpClient=HttpClientProvider.FileServiceHttpClient;
var queryString=string.Format(“?key={0}”,key);
var request=newhttprequestmessage(HttpMethod.Get,queryString);
var response=httpClient.SendAsync(请求).Result;
if(响应。IsSuccessStatusCode)
{
var metadata=newdictionary();
foreach(response.Headers中的var头)
{
//抓取tf头
if(header.Key.StartsWith(_metadataHeaderPrefix))
{
Add(header.Key.Substring(_metadataHeaderPrefix.Length),header.Value.First());
}
}
var virtualFile=新的virtualFile
{
QualifiedPath=key,
FileStream=response.Content.ReadAsStreamAsync().Result,
元数据=元数据
};
返回虚拟文件;
}
返回null;
默认空闲超时约为1-2分钟。之后,客户端必须与服务器重新握手。所以,你会发现100秒后它会变慢
您可以使用套接字处理程序来延长空闲超时
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionIdleTimeout = TimeSpan.FromHours(27),//Actually 5 mins can be idle at maximum. Note that timeouts longer than the TCP timeout may be ignored if no keep-alive TCP message is set at the transport level.
MaxConnectionsPerServer = 10
};
client = new HttpClient(socketsHandler);
如您所见,虽然我将空闲超时设置为27小时,但实际上它只保持5分钟的活动时间
因此,最后我只需每隔1分钟使用相同的HttpClient调用目标端点。在这种情况下,始终存在已建立的连接。您可以使用netstat来检查这一点。工作正常。您是否有代码示例,可以为我们提供更多您正在使用的内容?更新OP以添加代码
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionIdleTimeout = TimeSpan.FromHours(27),//Actually 5 mins can be idle at maximum. Note that timeouts longer than the TCP timeout may be ignored if no keep-alive TCP message is set at the transport level.
MaxConnectionsPerServer = 10
};
client = new HttpClient(socketsHandler);