.net core HttpClient 性能优化

1、使用HttpClientFactory工厂;

2、Startup里ConfigureServices添加HttpClient的具体的客户端服务;(注册到DI容器 )

services.AddHttpClient("SystemService", c =>
{
c.BaseAddress = new Uri(Configuration["ApiConfig:SystemService"]);
c.Timeout = TimeSpan.FromSeconds(30);
});

3、增加默认连接数和启用保活机制

在Program的Main方法里添加 

  //增加保活机制,表明连接为长连接
  client.DefaultRequestHeaders.Connection.Add("keep-alive");
  
  //启用保活机制(保持活动超时设置为 2 小时,并将保持活动间隔设置为 1 秒。)
  ServicePointManager.SetTcpKeepAlive(true, 7200000, 1000);
  
   //默认连接数限制为2,增加连接数限制
  ServicePointManager.DefaultConnectionLimit = 512;

4、尝试使用Socket通信连接

var client = new HttpClient(new SocketsHttpHandler()
{
    //考虑忽略使用代理
    UseProxy = false,
    //考虑增加连接数配置
    MaxConnectionsPerServer = 100,
    //考虑忽略重定向响应
    AllowAutoRedirect = false,
    //考虑忽略SSL证书验证
    SslOptions = new SslClientAuthenticationOptions()
    {
        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
    },
    //考虑数据压缩设置
    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
  })
  {
      BaseAddress = new Uri(""),
      Timeout = TimeSpan.FromSeconds(30),
  };
new HttpClient(new SocketsHttpHandler()看第一句代码。

作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
找一找教程网-随时随地学软件编程 http://www.zyiz.net/

原文地址:https://www.cnblogs.com/puzi0315/p/14870363.html