.net core 中并发请求发送HttpWebRequest的坑

栏目: ASP.NET · 发布时间: 7年前

内容简介:在framework中,大量并发 HttpWebRequest 需要设置一个最大连接数但是在.net core中却无效,因为core不使用 ServicePointManager 管理连接数,在core中只有使用HttpClient,HttpCilentFactory来管理连接数,如果在core中使用 ServicePointManager 不但不起作用,并且大量并发使用 HttpWebRequest 会导致 IIS 直接假死,所以在core中,只能使用 HttpClient 和 HttpCilentFa

在framework中,大量并发 HttpWebRequest 需要设置一个最大连接数

ServicePointManager.DefaultConnectionLimit = 200;

但是在.net core中却无效,因为core不使用 ServicePointManager 管理连接数,在core中只有使用HttpClient,HttpCilentFactory来管理连接数,如果在core中使用 ServicePointManager 不但不起作用,并且大量并发使用 HttpWebRequest 会导致 IIS 直接假死,所以在core中,只能使用 HttpClient 和 HttpCilentFactory这一条路可走

在Core中的StartUp注册一个HttpClient的名字

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient("HttpClientFactoryDemo");
        }

然后在Controller中创建

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Mvc;

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

        public ValuesController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public static string UrlEncode(string temp, Encoding encoding)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < temp.Length; i++)
            {
                string t = temp[i].ToString();
                string k = HttpUtility.UrlEncode(t, encoding);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString();
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            string xmlContent = "<?xml version=\"1.0\" encoding=\"GBK\" standalone=\"yes\"?><xml><version>1</version><ins_cd>08A9999999</ins_cd><mchnt_cd>0002900F0370588</mchnt_cd><term_id></term_id><random_str>93b4efa6d0d84808a76355ff0f7a178d</random_str><sign>G1+TBpyEVwsQjeJ9X7zrObRTFtI/ItuJWEEYl3AT/9XlFd844Jv2Wb/gNVkuEVP890Tf1Ub+EaTe1qByHSu97cpQr6riuDxqw2nnjKZBZsG00C1d8070sZPf4c1hkSUfhlR2nPn+7dvIanLCjRFzTgoTQ/WtcArrL/SJIJeaXYg=</sign><order_type>ALIPAY</order_type><goods_des>卡盟测试</goods_des><goods_detail></goods_detail><addn_inf></addn_inf><mchnt_order_no>2018121302054468584629</mchnt_order_no><curr_type></curr_type><order_amt>1</order_amt><term_ip>127.0.0.1</term_ip><txn_begin_ts>20181213020544</txn_begin_ts><goods_tag></goods_tag><auth_code>288232051781304899</auth_code><sence>1</sence><reserved_sub_appid></reserved_sub_appid><reserved_limit_pay></reserved_limit_pay></xml>";
            xmlContent = UrlEncode(xmlContent, Encoding.GetEncoding("GBK"));

            Dictionary<string, string> nvs = new Dictionary<string, string> { { "req", xmlContent } };
            Encoding encoding = Encoding.GetEncoding("GBK");
            StringBuilder buffer = new StringBuilder();
            int i = 0;
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(nvs);
            foreach (KeyValuePair<string, string> kvp in nvs)
            {
                buffer.AppendFormat(i > 0 ? "&{0}={1}" : "{0}={1}", kvp.Key,
                    UrlEncode(kvp.Value, Encoding.GetEncoding("GBK")));
                i++;
            }
            byte[] postBody = encoding.GetBytes(buffer.ToString());

            var client = _httpClientFactory.CreateClient("HttpClientFactoryDemo");
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri("https://spay.fuiou.com/commonQuery"),
                Method = HttpMethod.Post,
                Content = new ByteArrayContent(postBody),
            };

            request.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            return Ok(await client.SendAsync(request));

        }
    }
}

以上所述就是小编给大家介绍的《.net core 中并发请求发送HttpWebRequest的坑》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java并发编程的艺术

Java并发编程的艺术

方腾飞、魏鹏、程晓明 / 机械工业出版社 / 2015-7-1 / 59.00元

并发编程领域的扛鼎之作,作者是阿里和1号店的资深Java技术专家,对并发编程有非常深入的研究,《Java并发编程的艺术》是他们多年一线开发经验的结晶。本书的部分内容在出版早期发表在Java并发编程网和InfoQ等技术社区,得到了非常高的评价。它选取了Java并发编程中最核心的技术进行讲解,从JDK源码、JVM、CPU等多角度全面剖析和讲解了Java并发编程的框架、工具、原理和方法,对Java并发编......一起来看看 《Java并发编程的艺术》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具