具有动态配置的HttpClientFactory

时间:2018-11-14 14:40:51

标签: asp.net-core-2.1 .net-core-2.1 httpclientfactory

我正在使用.net核心Web应用程序,该应用程序需要以特定的时间间隔(每2分钟,20个不同的API调用,并且我需要向最终用户显示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吗?

0 个答案:

没有答案
相关问题