PHP 中的异步 Curl 请求
在 PHP 中异步执行 curl post 请求可以提高性能并防止潜在的延迟。以下是如何使用不同的方法实现此目的:
使用异步 cURL 函数
使用 curl_multi_* 时,您可以同时执行多个 cURL 请求。下面是示例代码:
<code class="php">$curl = curl_init($request); curl_setopt($curl, CURLOPT_URL, $url_onfleet); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_USERPWD, $api_onfleet); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, '{"destination":{"address":{"unparsed":"'.$pickup_address.'"},"notes":"'.$comments.'"},"recipients":[{"name":"'.$name.'","phone":"+61'.$phone.'","notes":"Number of riders: '.$riders.'"}],"completeBefore":'.$timestamp.',"pickupTask":"yes","autoAssign":{"mode":"distance"}}'); $mh = curl_multi_init(); curl_multi_add_handle($mh,$curl); $active = null; //execute the handles do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } //close the handles curl_multi_remove_handle($mh, $curl); curl_multi_close($mh);</code>
使用 pThreads
pThreads 是 PHP 的线程库。以下是如何将其用于异步curl请求:
<code class="php">class Request1 extends Thread { public function run() { // Execute the first cURL request here } } class Request2 extends Thread { public function run() { // Execute the second cURL request here } } $req1 = new Request1(); $req1->start(); $req2 = new Request2(); $req2->start();</code>
两种方法都允许异步执行curl请求,从而实现更好的性能和高效处理并行任务。
以上是如何在 PHP 中异步执行 cURL 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!