0

我正在尝试执行多个POSTREST 调用。问题:同时进行多个 POST 调用。我完全意识到并与图书馆合作过,guzzle但我还没有想办法正确地做到这一点。我可以GET异步执行调用,但没有任何相同级别的POST调用。然后我偶然发现pthreads并阅读了文档,并且对如何启动它感到有些困惑。我已经编译phppthreads扩展名。

有人可以建议如何同时执行多个POST呼叫并能够收集响应以供以后操作吗?

下面是一个循环和等待的基本实现。整体非常慢。

$postDatas = [
    ['field' => 'test'],
    ['field' => 'test1'],
    ['field' => 'test2'],
];

foreach ($postDatas as $postData) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL            => "https://www.apisite.com",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => "POST",
        CURLOPT_POSTFIELDS     => json_encode($postData),
        CURLOPT_HTTPHEADER     => [
            "cache-control: no-cache",
            "connection: keep-alive",
            "content-type: application/json",
            "host: some.apisite.com",
        ],
    ));

    $response = curl_exec($curl);
    $err      = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $response;
    }
}
4

1 回答 1

1

如果任务减少到使用 API,那么您可能需要使用http://php.net/manual/ru/function.curl-multi-exec.php

public function getMultiUrl() {
    //If the connections are very much split the queue into parts
    $parts = array_chunk($this->urlStack, self::URL_ITERATION_SIZE , TRUE);

    //base options
    $options = [
        CURLOPT_USERAGENT => 'MyAPP',
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
    ];

    foreach ($parts as $urls) {
        $mh = curl_multi_init();
        $active = null;
        $connects = [];
        foreach ($urls as $i => $url) {
            $options[CURLOPT_POSTFIELDS] = $url['postData']; 
            $connects[$i] = curl_init($url['queryUrl']);

            curl_setopt_array($connects[$i], $options);
            curl_multi_add_handle($mh, $connects[$i]);
        }

        do {
            $status = curl_multi_exec($mh, $active);
            $info = curl_multi_info_read($mh);
            if (false !== $info) {
                var_dump($info);
            }
        } while ($status === CURLM_CALL_MULTI_PERFORM || $active);

        foreach ($connects as $i => $conn) {
            $content = curl_multi_getcontent($conn);
            file_put_contents($this->dir . $i, $content);
            curl_close($conn);
        }
    }
}
于 2017-07-25T18:53:44.010 回答