简体   繁体   English

API调用因超出大量数据而超时

[英]API call getting timed out for large amout of data

I am having trouble in fetching XML data from through API in large amount. 我无法通过API大量获取XML数据。 Has anyone a better solution in fetching XML data in ASP.net application? 有没有人在ASP.net应用程序中获取XML数据更好的解决方案?

Maybe the issue is might be garbage collection memory not sure but earlier it was not working for any user so I added manual memory release code and closing web response connection after each call. 也许问题可能是垃圾收集内存不确定但早期它不适用于任何用户,因此我在每次调用后添加了手动内存释放代码并关闭Web响应连接。

Any suggestion to improve the fetching of large amount of data are welcome? 是否欢迎任何改进获取大量数据的建议?

   public static XmlDocument LoadXmlFromUrl(string url, bool keepAlive = true, bool throwException = false, int timeout = 15000)
    {
        Log(url, "*** start ***" + url);

        ServicePointManager.DefaultConnectionLimit = 2000;
        string xmlAsText = null;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.KeepAlive = keepAlive;
        req.Timeout = timeout; // 30,000ms = 30 sec default
        try
        {
            bool retried = false;
        retry:
            try
            {
                using (HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse())
                {
                    using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        xmlAsText = responseStream.ReadToEnd();
                        responseStream.Close();
                    }
                    webResponse.Close();

                    Log(url, "stream reader (responseStream.ReadToEnd) completed to string.");
                }
            }
            catch (WebException webEx)
            {
                if (!retried)
                {
                    if (webEx.Status == WebExceptionStatus.Timeout || webEx.Status == WebExceptionStatus.KeepAliveFailure)
                    {
                        Log(url, "About to retry for url (6 sec wait): " + url);
                        System.Threading.Thread.Sleep(6000);
                        retried = true;
                        goto retry;
                    }
                }
                else
                {
                    throw webEx;
                }
            }
        }
        catch (Exception ex)
        {
            Log(url, "exception while loading responseStream.ReadToEnd. " + ex.ToString());
        }
        XmlDocument xdoc = null;
        if (!string.IsNullOrEmpty(xmlAsText))
        {
            try
            {
                xdoc = new XmlDocument();
                xdoc.LoadXml(xmlAsText);
                Log(url, "string added to xml (xdoc.LoadXml) completed.");
            }
            catch (Exception ex)
            {
                Log(url, "exception while loading xdoc.LoadXml. " + ex.ToString());
            }
        }
        return xdoc;
    }

Exception 1: 例外1:

5/01/2017 12:27:01 p.m. exception while loading responseStream.ReadToEnd.     System.Net.WebException: The operation has timed out**

Exception 2: 例外2:

6/01/2017 8:35:59 a.m. exception while loading responseStream.ReadToEnd. System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

Exception #1 may occur if 如果是,可能会发生例外#1

  • request is huge. 请求很大。 In this case you can try to increase value of HttpWebRequest.ReadWriteTimeout to something relatively big, for example, 3600000 (1 hour). 在这种情况下,您可以尝试将HttpWebRequest.ReadWriteTimeout值增加到相对较大的值,例如3600000(1小时)。

  • value of header ContentLength does not match real response size and server does not force connection to close. 标头ContentLength值与实际响应大小不匹配,服务器不强制关闭连接。

To track down the problem I would suggest you to set up tracing. 为了追踪问题,我建议你设置跟踪。 You can follow https://msdn.microsoft.com/en-us/library/ty48b824(v=vs.110).aspx or find similar here on StackOverflow. 您可以关注https://msdn.microsoft.com/en-us/library/ty48b824(v=vs.110).aspx或在StackOverflow上找到类似的内容。

Exception #2 definitely occurs just because the response does not fit to memory allocated for application or its size exceeded 2Gb. 异常#2肯定是因为响应不适合为应用程序分配的内存或其大小超过2Gb。 (It must be really big response). (这一定是非常大的回应)。 The possible solution is to buffer stream to a file or process it on-fly (if possible). 可能的解决方案是将流缓冲到文件或在运行时处理它(如果可能)。 For example: 例如:

...
using (HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse())
{
    String tempFile = Path.GetTempFileName();
    using (var stream = webResponse.GetResponseStream())
    {
        if (stream != null)
        {
            using (FileStream file = File.Create(tempFile))
            {
                stream.CopyTo(file);
            }
        }
    }

    Log(url, "stream reader (responseStream.ReadToEnd) completed to string.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM