.NET Core中的HttpClientFactory类用法详解

一、HttpClient使用

在C#中,如果我们需要向某特定的URL地址发送Http请求的时候,通常会用到HttpClient类。会将HttpClient包裹在using内部进行声明和初始化,如下面的代码:

using (var httpClient = new HttpClient())
{
    // 逻辑处理代码
}

HttpClient类包含了许多有用的方法,使用上面的代码,可以满足绝大多数的需求,但是如果对其使用不当时,可能会出现意想不到的事情。

上面代码的技术范点:当你使用继承了IDisposable接口的对象时,建议在using代码块中声明和初始化,当using代码段执行完成后,会自动释放该对象而不需要手动进行显示Dispose操作。

对象所占用资源应该确保及时被释放掉,但是,对于网络连接而言,这是错误的。具体原因有下面两点:

  • 网络连接是需要耗费一定时间的,频繁开启与关闭连接,性能会受到影响。
  • 开启网络连接时会占用低层socket资源,但在HttpClient调用其本身的Dispose方法时,并不能立即释放该资源,这意味着你的程序可能会因为耗尽连接资源而产生预期之外的异常。

看下面一段代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HttpClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //using (var httpClient = new HttpClient())
            //{
            //    // 逻辑处理代码
            //}

            HttpAsync();
            Console.WriteLine("Hello World!");
            Console.Read();

        }

        public static async void HttpAsync()
        {
            for (int i = 0; i < 10; i++)
            {
                using (var client = new HttpClient())
                {
                    var result = await client.GetAsync("http://www.baidu.com");
                    Console.WriteLine($"{i}:{result.StatusCode}");
                }
            }
        }
    }
}

运行项目输出结果后,通过netstate查看下TCP连接情况,会发现连接依然存在,状态为“TIME_WAIT”(继续等待看是否还有延迟的包会传输过来)。

这里就会出现一个坑:在高并发的情况下,连接来不及释放,socket连接被耗尽,耗尽之后就会出现错误。就是会出现“各种套接字问题”。

那么如何解决这个问题呢?比较好的解决方法是延长HttpClient对象的使用寿命,实现HttpClient对象的复用,比如对其建一个静态的对象:

private static HttpClient Client = new HttpClient();

我们使用这种方式优化上面的代码

using System;
using System.Net.Http;

namespace HttpClientDemo
{
    class Program
    {
        private static readonly HttpClient _client = new HttpClient();
        static void Main(string[] args)
        {
            HttpAsync();
            Console.WriteLine("Hello World");
            Console.ReadKey();
        }

        public static async void HttpAsync()
        {
            for (int i = 0; i < 10; i++)
            {
                var result = await _client.GetAsync("http://www.baidu.com");
                Console.WriteLine($"{i}:{result.StatusCode}");
            }
        }

    }
}

这样调整HttpClient的引用后,虽然可以解决一些问题,但是仍然存在一些问题:

  • 因为是复用的HttpClient,那么一些公共的设置就没办法灵活的调整,如请求头的自定义。
  • 因为HttpClient请求每个url时,会缓存url对应的主机ip,从而会导致DNS更新失效。

为了解决这些问题,在.NET Core 2.1中引入了新的HttpClientFactory类。

二、HttpClientFactory使用

微软在.NET Core 2.1中新引入了HttpClientFactory类,具有如下的优势:

  • HttpClientFactory很高效,可以最大程度上节省系统的sock而。
  • Factory,顾名思义HttpClientfactory就是HttpClient的工厂,内部已经帮我们处理好了对HttpClient的管理,不需要我们人工进行对象释放,同时,支持自定义请求头、支持DNS更新等。

我们用一个ASP.NET Core的程序作为示例,它的用法非常简单,首先是对其进行IOC注册:

public void ConfigureServices(IServiceCollection services)
{
    // 注入HttpClient
    services.AddHttpClient("client_1", config =>  //这里指定的name=client_1,可以方便我们后期服用该实例
    {
        config.BaseAddress = new Uri("http://www.baidu.com");
        config.DefaultRequestHeaders.Add("header_1", "header_1");
    });
    services.AddHttpClient("client_2", config =>
    {
        config.BaseAddress = new Uri("https://www.qq.com/");
        config.DefaultRequestHeaders.Add("header_2", "header_2");
    });
    services.AddHttpClient();
    services.AddControllers();
}

然后在控制器里面通过IHttpClientFactory创建一个HttpClient对象,之后的操作跟以前一样,但不需要担心其内部资源的释放:

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace HttpClientFactoryDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 通过构造函数实现注入
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public DemoController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<string> Get()
        {
            var client = _httpClientFactory.CreateClient("client_1"); //复用在Startup中定义的client_1的httpclient
            var result = await client.GetStringAsync("/page1.html");

            var client2 = _httpClientFactory.CreateClient(); //新建一个HttpClient
            var result2 = await client.GetAsync("http://www.baidu.com");

            return result2.StatusCode.ToString();
        }
    }
}

程序运行结果:

AddHttpClient的源码:

public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddLogging();
    services.AddOptions();

    //
    // Core abstractions
    //
    services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
    services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();

    //
    // Typed Clients
    //
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>)));

    //
    // Misc infrastructure
    //
    services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>());

    return services;
}

看下面这句代码:

services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();

这里添加依赖注入的时候为IHttpClientFactory接口绑定了DefaultHttpClientFactory类。

我们在来看IHttpClientFactory接口中关键的CreateClient方法:

public HttpClient CreateClient(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    var entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value;
    var client = new HttpClient(entry.Handler, disposeHandler: false);

    StartHandlerEntryTimer(entry);

    var options = _optionsMonitor.Get(name);
    for (var i = 0; i < options.HttpClientActions.Count; i++)
    {
        options.HttpClientActions[i](client);
    }

    return client;
}

从代码中我们可以看出:HttpClient的创建不在是简单的new HttpClient(),而是传入了两个参数:HttpMessageHandler handler与bool disposeHandler。

disposeHandler参数为false时表示要重用内部的handler对象。handler参数则从上一句的代码中可以看出是以name为键值从一字典中取出,又因为DefaultHttpClientFactory类是通过TryAddSingleton方法注册的,也就意味着其为单例,那么这个内部字典便是唯一的,每个键值对应的ActiveHandlerTrackingEntry对象也是唯一,该对象内部中包含着handler。

下一句代码StartHandlerEntryTimer(entry); 开启了ActiveHandlerTrackingEntry对象的过期计时处理。默认过期时间是2分钟。

internal void ExpiryTimer_Tick(object state)
{
    var active = (ActiveHandlerTrackingEntry)state;

    // The timer callback should be the only one removing from the active collection. If we can't find
    // our entry in the collection, then this is a bug.
    var removed = _activeHandlers.TryRemove(active.Name, out var found);
    Debug.Assert(removed, "Entry not found. We should always be able to remove the entry");
    Debug.Assert(object.ReferenceEquals(active, found.Value), "Different entry found. The entry should not have been replaced");

    // At this point the handler is no longer 'active' and will not be handed out to any new clients.
    // However we haven't dropped our strong reference to the handler, so we can't yet determine if
    // there are still any other outstanding references (we know there is at least one).
    //
    // We use a different state object to track expired handlers. This allows any other thread that acquired
    // the 'active' entry to use it without safety problems.
    var expired = new ExpiredHandlerTrackingEntry(active);
    _expiredHandlers.Enqueue(expired);

    Log.HandlerExpired(_logger, active.Name, active.Lifetime);

    StartCleanupTimer();
}

先是将ActiveHandlerTrackingEntry对象传入新的ExpiredHandlerTrackingEntry对象。

public ExpiredHandlerTrackingEntry(ActiveHandlerTrackingEntry other)
{
    Name = other.Name;

    _livenessTracker = new WeakReference(other.Handler);
    InnerHandler = other.Handler.InnerHandler;
}

在其构造方法内部,handler对象通过弱引用方式关联着,不会影响其被GC释放。

然后新建的ExpiredHandlerTrackingEntry对象被放入专用的队列。

最后开始清理工作,定时器的时间间隔设定为每10秒一次。

internal void CleanupTimer_Tick(object state)
{
    // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup.
    //
    // With the scheme we're using it's possible we could end up with some redundant cleanup operations.
    // This is expected and fine.
    //
    // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it
    // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out
    // whether we need to start the timer.
    StopCleanupTimer();

    try
    {
        if (!Monitor.TryEnter(_cleanupActiveLock))
        {
            // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes
            // a long time for some reason. Since we're running user code inside Dispose, it's definitely
            // possible.
            //
            // If we end up in that position, just make sure the timer gets started again. It should be cheap
            // to run a 'no-op' cleanup.
            StartCleanupTimer();
            return;
        }

        var initialCount = _expiredHandlers.Count;
        Log.CleanupCycleStart(_logger, initialCount);

        var stopwatch = ValueStopwatch.StartNew();

        var disposedCount = 0;
        for (var i = 0; i < initialCount; i++)
        {
            // Since we're the only one removing from _expired, TryDequeue must always succeed.
            _expiredHandlers.TryDequeue(out var entry);
            Debug.Assert(entry != null, "Entry was null, we should always get an entry back from TryDequeue");

            if (entry.CanDispose)
            {
                try
                {
                    entry.InnerHandler.Dispose();
                    disposedCount++;
                }
                catch (Exception ex)
                {
                    Log.CleanupItemFailed(_logger, entry.Name, ex);
                }
            }
            else
            {
                // If the entry is still live, put it back in the queue so we can process it
                // during the next cleanup cycle.
                _expiredHandlers.Enqueue(entry);
            }
        }

        Log.CleanupCycleEnd(_logger, stopwatch.GetElapsedTime(), disposedCount, _expiredHandlers.Count);
    }
    finally
    {
        Monitor.Exit(_cleanupActiveLock);
    }

    // We didn't totally empty the cleanup queue, try again later.
    if (_expiredHandlers.Count > 0)
    {
        StartCleanupTimer();
    }
}

上述方法核心是判断是否handler对象已经被GC,如果是的话,则释放其内部资源,即网络连接。

回到最初创建HttpClient的代码,会发现并没有传入任何name参数值。这是得益于HttpClientFactoryExtensions类的扩展方法。

public static HttpClient CreateClient(this IHttpClientFactory factory)
{
    if (factory == null)
    {
        throw new ArgumentNullException(nameof(factory));
    }

    return factory.CreateClient(Options.DefaultName);
}

Options.DefaultName的值为string.Empty。

到此这篇关于.NET Core中的HttpClientFactory类用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • asp.net core为IHttpClientFactory添加动态命名配置

    目录 官方有什么推荐么? IHttpClientFactory.CreateClient是如何将HttpClient创建出来的? 扩展点一的实现 扩展点二的实现 使用 总结一下 比如如何使用IHttpClientFactory动态添加cer证书 有三种方法推荐方法 方法一: 推荐的做法是这样子 services.AddHttpClient("a业务").ConfigurePrimaryHttpMessageHandler(...a业务证书) services.AddHttpClient

  • 如何利用HttpClientFactory实现简单的熔断降级

    前言 在2.1之后,有不少新东西,其中HttpClientFactory算是一个.HttpClientFactory涉及的东西也不算少,三四种clients , 请求中间件,与Polly的结合,生命周期等. Steeltoe的组件升级到2.1后,不少示例代码已经使用HttpClientFactory了.当然这是个题外话. 这里主要讲的是与Polly的结合,来完成简单的熔断降级.在这之前,还是先看看关于HttpClientFactory最简单的用法. HttpClientFactory的简单使用

  • 如何在ASP.NET Core中使用HttpClientFactory

    ASP.Net Core 是一个开源的,跨平台的,轻量级模块化框架,可用它来构建高性能的Web程序,这篇文章我们将会讨论如何在 ASP.Net Core 中使用 HttpClientFactory. 为什么要使用 HttpClientFactory 可以用 HttpClientFactory 来集中化管理 HttpClient,工厂提供了对 HttpClient 的创建,配置和调度,值得一提的是:HttpClient 一直都是 Http 请求业务方面的一等公民. HttpClient 虽好,但它

  • .Net Core下HTTP请求IHttpClientFactory示例详解

    使用方式 IHttpClientFactory有四种模式: 基本用法 命名客户端 类型化客户端 生成的客户端 基本用法 在 Startup.ConfigureServices 方法中,通过在 IServiceCollection 上调用 AddHttpClient 扩展方法可以注册 IHttpClientFactory services.AddHttpClient(); 注册之后可以像依赖注入DI似得在类中通过构造函数注入形式使用,伪代码: class A { private readonly

  • 详解如何在ASP.NET Core中使用IHttpClientFactory

    利用IHttpClientFactory可以无缝创建HttpClient实例,避免手动管理它们的生命周期. 当使用ASP.Net Core开发应用程序时,可能经常需要通过HttpClient调用WebAPI的方法以检查终结点是否正常工作.要实现这一点,通常需要实例化HttpClient并使用该实例来调用你的方法.但是直接使用HttpClient也有一些缺点,主要与手动管理实例的生命周期有关. 你可以使用IHttpClientFactory创建HttpClient来避免这些问题.IHttpClie

  • .net Core 使用IHttpClientFactory请求实现

    导读:本文已添加在 晨曦微服务之旅 ,现在自己在尝试微服务架构,一边学边做项目快速的进入状态.当然在学习的过程中会将自己学到的知识进行分享. 一.为什么不用HttpClient 1.HttPClient使用完之后不会立即关闭开启网络连接时会占用底层socket资源,但在HttpClient调用其本身的Dispose方法时,并不能立刻释放该资源 2.如果频繁的使用HttpClient,频繁的打开链接,关闭链接消耗就会很大. 二.解决方案 1.我们可以延长HttpClient的生命周期,比如对其建一

  • DotNetCore深入了解之HttpClientFactory类详解

    当需要向某特定URL地址发送HTTP请求并得到相应响应时,通常会用到HttpClient类.该类包含了众多有用的方法,可以满足绝大多数的需求.但是如果对其使用不当时,可能会出现意想不到的事情. using(var client = new HttpClient()) 对象所占用资源应该确保及时被释放掉,但是,对于网络连接而言,这是错误的. 原因有二,网络连接是需要耗费一定时间的,频繁开启与关闭连接,性能会受影响:再者,开启网络连接时会占用底层socket资源,但在HttpClient调用其本身的

  • .NET Core 2.1中HttpClientFactory的最佳实践记录

    前言 ASP.NET Core 2.1中出现一个新的HttpClientFactory功能, 它有助于解决开发人员在使用HttpClient实例从其应用程序发出外部Web请求时可能遇到的一些常见问题. 介绍 在.NETCore平台的2.1新增了HttpClientFactory,虽然HttpClient这个类实现了disposable,但使用它的时候用声明using包装块的方式通常不是最好的选择.处理HttpClient,底层socket套接字不会立即释放.该HttpClient类是专为多个请求

  • .NET Core中的HttpClientFactory类用法详解

    一.HttpClient使用 在C#中,如果我们需要向某特定的URL地址发送Http请求的时候,通常会用到HttpClient类.会将HttpClient包裹在using内部进行声明和初始化,如下面的代码: using (var httpClient = new HttpClient()) { // 逻辑处理代码 } HttpClient类包含了许多有用的方法,使用上面的代码,可以满足绝大多数的需求,但是如果对其使用不当时,可能会出现意想不到的事情. 上面代码的技术范点:当你使用继承了IDisp

  • ASP.NET Core中Cookie验证身份用法详解

    目录 添加配置 ASP.NETCore1.x ASP.NETCore2.x 创建身份认证Cookie ASP.NETCore1.x ASP.NETCore2.x Signingout(登出) ASP.NETCore1.x ASP.NETCore2.x 服务端变化反馈 ASP.NETCore1.x ASP.NETCore2.x Cookie设置选项 ASP.NETCore1.x ASP.NETCore2.x 持久Cookie ASP.NETCore1.x ASP.NETCore2.x 绝对到期时间

  • C#中的HttpWebRequest类用法详解

    HttpWebRequest 是一个Http 请求类,继承于 WebRequest. WebRequest 是一个抽象类,能够对统一资源标识符 (URI) 发出请求. WebRequest 有以下派生类: System.IO.Packaging.PackWebRequest System.Net.FileWebRequest System.Net.FtpWebRequest System.Net.HttpWebRequest 使用时 using System.Net; 1,HttpWebRequ

  • JavaWeb中过滤器Filter的用法详解

    目录 过滤器Filter 处理顺序 使用场景 自定义过滤器 源码分析 FilterDef FilterMap 初始化过滤器 创建过滤器链 ApplicationFilterChain 执行过滤器链 过滤器Filter 过滤器通常对一些web资源进行拦截,做完一些处理器再交给下一个过滤器处理,直到所有的过滤器处理器,再调用servlet实例的service方法进行处理.过滤器可以对request进行处理也可以对response进行处理. 处理顺序 如果过滤器链顺序如上图所示,那么对request请

  • Oracle中游标Cursor基本用法详解

    查询 SELECT语句用于从数据库中查询数据,当在PL/SQL中使用SELECT语句时,要与INTO子句一起使用,查询的 返回值被赋予INTO子句中的变量,变量的声明是在DELCARE中.SELECT INTO语法如下: SELECT [DISTICT|ALL]{*|column[,column,...]} INTO (variable[,variable,...] |record) FROM {table|(sub-query)}[alias] WHERE............ PL/SQL

  • Python3网络爬虫中的requests高级用法详解

    本节我们再来了解下 Requests 的一些高级用法,如文件上传,代理设置,Cookies 设置等等. 1. 文件上传 我们知道 Reqeuests 可以模拟提交一些数据,假如有的网站需要我们上传文件,我们同样可以利用它来上传,实现非常简单,实例如下: import requests files = {'file': open('favicon.ico', 'rb')} r = requests.post('http://httpbin.org/post', files=files) print

  • PyTorch中topk函数的用法详解

    听名字就知道这个函数是用来求tensor中某个dim的前k大或者前k小的值以及对应的index. 用法 torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) -> (Tensor, LongTensor) input:一个tensor数据 k:指明是得到前k个数据以及其index dim: 指定在哪个维度上排序, 默认是最后一个维度 largest:如果为True,按照大到小排序: 如果为False,按照小到大排序

  • Django admin管理工具TabularInline类用法详解

    TabularInline类用于在A页面上编辑B表的字段,举例说明,如果models.py中有Staff.Job两个model: from django.db import models class Staff(models.Model): name = models.CharField(max_length=10) class Job(models.Model): staff = models.ForeignKey(Staff) task = models.CharField(max_leng

  • java8中的Collectors.groupingBy用法详解

    Collectors.groupingBy根据一个或多个属性对集合中的项目进行分组 数据准备: public Product(Long id, Integer num, BigDecimal price, String name, String category) { this.id = id; this.num = num; this.price = price; this.name = name; this.category = category; } Product prod1 = new

  • Java String类用法详解

    一.简介 零碎知识点 extends Object implements serializable,Comparable< String >,charSequence String类表示字符串,所有字符串文字都是此类的对象 字符串是不变的,值在创建后无法更改 对象一旦声明则不可改变,改变的只是地址,原来的字符串还是存在的,并且产生垃圾 任何一个""都为字符串对象,无赋值则为匿名对象 用"+"拼接字符串尽量避免,一般用append+toString Str

随机推荐