.net core并发请求发送HttpWebRequest的坑解决
在framework中,大量并发HttpWebRequest需要设置一个最大连接数
ServicePointManager.DefaultConnectionLimit=200;
但是在.netcore中却无效,因为core不使用 ServicePointManager管理连接数,在core中只有使用HttpClient,HttpCilentFactory来管理连接数,如果在core中使用 ServicePointManager不但不起作用,并且大量并发使用 HttpWebRequest会导致IIS直接假死,所以在core中,只能使用 HttpClient和HttpCilentFactory这一条路可走
在Core中的StartUp注册一个HttpClient的名字
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddHttpClient("HttpClientFactoryDemo");
}
然后在Controller中创建
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Net.Http;
usingSystem.Net.Http.Headers;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Web;
usingMicrosoft.AspNetCore.Mvc;
namespaceHttpClientFactoryDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
publicclassValuesController:ControllerBase
{
privatereadonlyIHttpClientFactory_httpClientFactory;
publicValuesController(IHttpClientFactoryhttpClientFactory)
{
_httpClientFactory=httpClientFactory;
}
publicstaticstringUrlEncode(stringtemp,Encodingencoding)
{
StringBuilderstringBuilder=newStringBuilder();
for(inti=0;iGet()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
stringxmlContent="1 08A9999999 0002900F0370588 93b4efa6d0d84808a76355ff0f7a178d G1+TBpyEVwsQjeJ9X7zrObRTFtI/ItuJWEEYl3AT/9XlFd844Jv2Wb/gNVkuEVP890Tf1Ub+EaTe1qByHSu97cpQr6riuDxqw2nnjKZBZsG00C1d8070sZPf4c1hkSUfhlR2nPn+7dvIanLCjRFzTgoTQ/WtcArrL/SJIJeaXYg= ALIPAY 卡盟测试 2018121302054468584629 1 127.0.0.1 20181213020544 288232051781304899 1 ";
xmlContent=UrlEncode(xmlContent,Encoding.GetEncoding("GBK"));
Dictionarynvs=newDictionary{{"req",xmlContent}};
Encodingencoding=Encoding.GetEncoding("GBK");
StringBuilderbuffer=newStringBuilder();
inti=0;
IDictionarysortedParams=newSortedDictionary(nvs);
foreach(KeyValuePairkvpinnvs)
{
buffer.AppendFormat(i>0?"&{0}={1}":"{0}={1}",kvp.Key,
UrlEncode(kvp.Value,Encoding.GetEncoding("GBK")));
i++;
}
byte[]postBody=encoding.GetBytes(buffer.ToString());
varclient=_httpClientFactory.CreateClient("HttpClientFactoryDemo");
varrequest=newHttpRequestMessage
{
RequestUri=newUri("https://spay.fuiou.com/commonQuery"),
Method=HttpMethod.Post,
Content=newByteArrayContent(postBody),
};
request.Content.Headers.ContentType=
newMediaTypeHeaderValue("application/x-www-form-urlencoded");
returnOk(awaitclient.SendAsync(request));
}
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。