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()看第一句代碼。