首页 > 解决方案 > Curl - 发送数百个请求,但一次只发送四个 - 编程

问题描述

你如何着手解决这个问题?我有数百个请求要发送到 Curl,但我一次只能发送四个。

因此,我需要同时使用 curl 发出四个请求并处理它们的响应。但是,一旦有一个 curl 指针可用,我需要发送另一个请求。

这是因为,服务器一次只能处理四个请求,但我有数百个请求要发送到服务器。

以下是我从 curl 网站获得的代码

    int main(void)
    {
      const int HANDLECOUNT = 4;
      CURL *handles[HANDLECOUNT];
      CURLM *multi_handle;

      int still_running = 0; /* keep number of running handles */ 
      int i;

      CURLMsg *msg; /* for picking up messages with the transfer status */ 
      int msgs_left; /* how many messages are left */ 

      /* Allocate one CURL handle per transfer */ 
      for(i = 0; i<HANDLECOUNT; i++)
        handles[i] = curl_easy_init();

      /* set the options (I left out a few, you'll get the point anyway) */ 
      curl_easy_setopt(handles[0], CURLOPT_URL, "website");
      curl_easy_setopt(handles[0], CURLOPT_POSTFIELDS, XMLRequestToPost.c_str());
      curl_easy_setopt(handles[0], CURLOPT_POSTFIELDSIZE, (long)strlen(XMLRequestToPost.c_str())); 
      curl_easy_setopt(handles[1], CURLOPT_URL, "website");     
      curl_easy_setopt(handles[2], CURLOPT_URL, "website");    
      curl_easy_setopt(handles[3], CURLOPT_URL, "website");    

      /* set the request for other 3 handles too */
      /* init a multi stack */ 
      multi_handle = curl_multi_init();

      /* add the individual transfers */ 
      for(i = 0; i<HANDLECOUNT; i++)
        curl_multi_add_handle(multi_handle, handles[i]);

      /* we start some action by calling perform right away */ 
      curl_multi_perform(multi_handle, &still_running);

      while(still_running) {
      }


     }

标签: c++visual-studiocurlvisual-c++libcurl

解决方案


创建一个线程安全队列来放入您的请求。

启动 4 个线程,每个线程都有自己的 CURL 对象。

让每个线程运行一个循环:

  • 从队列中拉下一个请求,
  • 发送它
  • 根据需要处理/发送响应,
  • 并重复

直到队列为空。


推荐阅读