我正在开发 .net 核心网络应用程序,它需要以特定的时间间隔调用远程 API(每 2 分钟,20 次不同的 API 调用,我需要向最终用户显示 API 结果),托管有4 个不同的域名
我使用 HttpClient 来调用远程 API。但是随着用户的增加,我的 CPU 使用率增加了 40%。我怀疑 HttpClient 可能是原因。在浏览了几篇博客之后,我正在尝试使用 HttpClientFactory。
我有一个从 Controller Action 调用的方法,我需要根据几个参数动态识别 BaseUrl 。目前我在 StartUp.cs 中创建了 4 个 NamedClients,如下所示:
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
});
然后像这样在课堂上使用:
public class Service : IService
{
private readonly IHttpClientFactory httpClientFactory;
public Service(IHttpClientFactory clientFactory)
{
httpClientFactory = clientFactory;
}
public HttpResponseMessage GetApiClientResponse(string displayName, IConfiguration configuration, HttpRequest httpRequest)
{
var endPoint = ApiConfig.GetApiDetail(configuration).
SingleOrDefault(ep => ep.DisplayName.ToLower().Equals(displayName.ToLower()));
var client = httpClientFactory.CreateClient(endPoint.NamedClient);
HttpResponseMessage response = null;
try
{
response = client.GetAsync(new Uri(endPoint.EndPointName,UriKind.Relative), HttpCompletionOption.ResponseHeadersRead).Result;
}
catch { ...}
return response;
}
}
在这里,根据 displayname 参数,我可以决定使用哪个 NamedClient。
有没有其他有效的方法来实现所需的功能?我可以改用 TypedClient 吗?